Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use INotifyPropertyChanged to update an array binding?

Tags:

wpf

Let's say I have a class:

class Foo
{
  public string Bar
  {
    get { ... }
  }

  public string this[int index]
  {
    get { ... }
  }
}

I can bind to these two properties using "{Binding Path=Bar}" and "{Binding Path=[x]}". Fine.

Now let's say I want to implement INotifyPropertyChanged:

class Foo : INotifyPropertyChanged
{
  public string Bar
  {
    get { ... }
    set
    {
      ...

      if( PropertyChanged != null )
      {
        PropertyChanged( this, new PropertyChangedEventArgs( "Bar" ) );
      }
    }
  }

  public string this[int index]
  {
    get { ... }
    set
    {
      ...

      if( PropertyChanged != null )
      {
        PropertyChanged( this, new PropertyChangedEventArgs( "????" ) );
      }
    }
  }

  public event PropertyChangedEventHandler PropertyChanged;
}

What goes in the part marked ????? (I've tried string.Format("[{0}]", index) and it doesn't work). Is this a bug in WPF, is there an alternative syntax, or is it simply that INotifyPropertyChanged isn't as powerful as normal binding?

like image 291
stusmith Avatar asked Sep 18 '08 08:09

stusmith


People also ask

How do you use INotifyPropertyChanged?

To implement INotifyPropertyChanged you need to declare the PropertyChanged event and create the OnPropertyChanged method. Then for each property you want change notifications for, you call OnPropertyChanged whenever the property is updated.

Does ObservableCollection implement INotifyPropertyChanged?

ObservableCollection implements INotifyCollectionChanged which will notify us when the collection has a mutated state. This means creates, adds, updates, deletes. Very few of us are explained this difference when we come to MVVM.

What is INotifyPropertyChanged in WPF?

The INotifyPropertyChanged interface is used to notify clients, typically binding clients, that a property value has changed. For example, consider a Person object with a property called FirstName .


2 Answers

Thanks to Cameron's suggestion, I've found the correct syntax, which is:

Item[]

Which updates everything (all index values) bound to that indexed property.

like image 81
stusmith Avatar answered Sep 20 '22 12:09

stusmith


Avoiding strings in your code, you can use the constant Binding.IndexerName, which is actually "Item[]"

new PropertyChangedEventArgs(Binding.IndexerName)
like image 24
Adi Lester Avatar answered Sep 21 '22 12:09

Adi Lester