Reputation: 6222
I have a theoretical problem.
<ListBox ItemSource= "{Binding Fruits}" >
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Color}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox
Let's assume I have ObservableCollection<Fruit> Fruits
in my ViewModel.
Fruit is not my class so I can't implement INotifyPropertyChanged
when Fruit Color changes.
I know in my ViewModel when these properties are changed for example:
public ChangeColor()
{
Fruits[1].Color = "Blue";
//Notify Fruits Here, How?
}
INotifyPropertyChanged
behind the scenes? If I have ObservableCollection<Fruit> Fruits
and Fruit Color property changes it is sent something like NotifyPropertyChanged("Fruits.Name")
?Upvotes: 0
Views: 167
Reputation: 657
public class FruitsEx : Fruits, INotifyPropertyChanged { public Color ColorEx { get { return this.Color; } set { this.Color = value;
if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("ColorEx")); } } } // INotifyPropertyChanged event public event PropertyChangedEventHandler PropertyChanged; public void NotifyPropertyChanged(string propertyName) { if (PropertyChanged != null) {
PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } }
In this way, you may use the ColorEx property to notify the changes.
One thing to keep in mind is that, if you do
new ObservableCollection<T>()
the target will not be updated. Because ObservableCollection by itself does not implement notify mechanism.
Upvotes: 1
Reputation: 2001
As Jehof mentioned in the comments, the key here is to create a FruitViewModel to wrap your fruit model. In that case you will need to tell a specific FruitviewModel to call OnPropertyChanged on one of its properties to work. ("Fruits.Name") will not work.
Upvotes: 0