When one wants to have a collection of values, and be notify when that collection changes, the ObservableCollection
and its CollectionChanged
event can be used.
However, its CollectionChanged
event is only fired when modifying the collection itself, not the values it contains. For example, if I have an ObservableCollection<Image>
, I won't be able to detect when someone accesses the N-th image of the collection and calls a method that modifies it. he same thing is true if I have an ObservableCollection<Color>
. If I want to be able to monitor when a Color struct contained within the list is assigned, the items themselves must be observable (recursively). A Color
struct not being observable, I want to encapsulate it into a struct called ObservableColor
.
The problem is that, the compiler is yelling at me because the event is not being initialized in the constructor. Well first I didn't know an event had to be initialized, and second I have no idea how it is supposed to be initialized.
Below is my code :
struct ObservableColor : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public Color Value { get; private set; }
public ObservableColor(Color color)
{
Value = color;
}
public void Set(Color color)
{
Color oldColor = Value;
Value = color;
if (Value != oldColor)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Value"));
}
}
}
How can I make this compile ? Thank you.