MistyK
MistyK

Reputation: 6222

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

Upvotes: 0

Views: 167

Answers (2)

captainst
captainst

Reputation: 657

  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:
    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.

  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.

Upvotes: 1

ArielBH
ArielBH

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

Related Questions