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")
?\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.
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.