In my C# application, I have two ObservableCollection properties:
public ObservableCollection<Material> Materials { get; init; } = new();
public ObservableCollection<string> MaterialNames
{
get
{
ObservableCollection<string> names = new();
foreach (Material material in Materials)
{
names.Add(material.Name);
}
return names;
}
}
The second property shadows the first one, returning Name from the objects in the first list. A WPF ListBox is binded to this second property. What I need is for the second list to fire an update when members are added or removed from the first one, so that the ListBox updates. Right now, that doesn't happen. What is the easiest solution to implement this, "connecting" the notifications of both ObservableCollections?
Disclaimer: I know it is easier to bind to the first property and set DisplayMemberPath to Name, but due to certain constrains in the application I need to bind to a separate property.
The easiest approach is to use an immutable collection as the source, and just replace the entire collections when needed. All changes must be done by replacing the immutable collection.
You can do things like projecting changes from one list to another, just listen to
CollectionChangedand replicate the changes to your other collection. But I find it fairly difficult to figure out exactly what have changed. So my personal preference is to use a custom list with more informative events I can use to replicate changes to a ObservableCollection.If you need to serialize this data I would recommend creating separate "Data Transfer Objects" (DTOs) that only includes plain lists/arrays that can be handled by the serialization library. You can then create your UI model from this. That way you are not mixing UI concerns with serialization concerns.
But the better solution is almost certainly to address whatever issues that prevent you from just using
DisplayMemberPath