简体   繁体   中英

WPF Binding INotifyPropertyChanged

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?
}
  1. How to do that?
  2. How it works when implementing INotifyPropertyChanged behind the scenes? If I have ObservableCollection<Fruit> Fruits and Fruit Color property changes it is sent something like NotifyPropertyChanged("Fruits.Name") ?
  1. By "Fruit is not my class", you mean that the class Fruit is written by someone else or encapsulated into some dll? If so, you may still subclass Fruit and implement INotifyPropertyChanged interface, something like:
    \npublic class FruitsEx : Fruits, INotifyPropertyChanged\n{ \n    public Color ColorEx\n    { \n        get { return this.Color; } \n        set\n        { \n            this.Color = value; 
    \n if (PropertyChanged != null) \n { \n PropertyChanged(this, new PropertyChangedEventArgs("ColorEx")); \n } \n } \n } \n // INotifyPropertyChanged event \n public event PropertyChangedEventHandler PropertyChanged;\n public void NotifyPropertyChanged(string propertyName) \n { \n if (PropertyChanged != null) \n {
    \n PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); \n } \n } \n}

In this way, you may use the ColorEx property to notify the changes.

  1. INotifyPropertyChanged and ObservableCollection serve different purpose. ObservableCollection will update the target list when item in the collection changes (for example, added or removed). But if you want to change, say, the color of an item in the collection, you need to implement INotifyPropertyChanged for the item.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM