如何使用INotifyPropertyChanged更新数组绑定?

时间:2020-03-06 14:20:25  来源:igfitidea点击:

假设我有一堂课:

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

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

我可以使用" {Binding Path = Bar}"和" {Binding Path = [x]}"绑定到这两个属性。美好的。

现在假设我要实现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;
}

标为??????的部分内容(我尝试过string.Format(" [{{0}]",index),它不起作用。这是WPF中的错误吗?是否存在替代语法?或者仅仅是INotifyPropertyChanged不如常规绑定那么强大?

解决方案

不确定是否可以使用,但是反射器显示索引属性的get和set方法称为get_Item和set_Item。也许我们可以尝试使用Item看看是否可行。

感谢Cameron的建议,我找到了正确的语法,即:

Item[]

它将更新绑定到该索引属性的所有内容(所有索引值)。

PropertyChanged( this, new PropertyChangedEventArgs( "Item[]" ) )

对于所有索引和

PropertyChanged( this, new PropertyChangedEventArgs( "Item[" + index + "]" ) )

对于单个项目

问候,杰罗德