C#WPF绑定到索引属性 – 我做错了什么?

我最近发现了索引属性。 这看起来像是我正在使用的数据最好在集合中表示的场景的完美解决方案,但仍然需要实现为可以在XAML数据绑定中使用的属性。 我开始只是测试创建索引属性,我没有遇到任何问题,但我似乎无法使绑定工作。

谁能指出我哪里出错?

这是带有嵌套类的测试类,用于创建索引属性:

public class TestListProperty { public readonly ListProperty ListData; //--------------------------- public class ListProperty : INotifyPropertyChanged { private List m_data; internal ListProperty() { m_data = new List(); } public string this[int index] { get { if ( m_data.Count > index ) { return m_data[index]; } else { return "Element not set for " + index.ToString(); } } set { if ( m_data.Count > index ) { m_data[index] = value; } else { m_data.Insert( index, value ); } OnPropertyChanged( "Item[]" ); Console.WriteLine( value ); } } public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged( string propertyName ) { PropertyChangedEventHandler handler = PropertyChanged; if ( handler != null ) handler( this, new PropertyChangedEventArgs( propertyName ) ); } } //--------------------------- public TestListProperty() { ListData = new ListProperty(); } } 

这是XAML:

             

这是窗口代码:

 public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); TestListProperty test = new TestListProperty(); this.DataContext = test; test.ListData[0] = "ABC"; test.ListData[1] = "Pleeez 2 wurk?"; test.ListData[2] = "Oh well"; } } 

感谢您的帮助!

当列表发生更改时,代码中没有机制指示前端,即ListProperty正在实现INotifyPropertyChanged而不是INotifyCollectionChanged。 最简单的解决方法是将m_data更改为类型ObservableCollection并将XAML控件绑定到该控件,尽管这可能会破坏您首先尝试执行的操作的目的。 “正确”的方式是订阅CollectionChanged事件并通过以下方式传播消息:

 public class TestListProperty { public ListProperty ListData { get; private set; } //--------------------------- public class ListProperty : INotifyCollectionChanged { private ObservableCollection m_data; internal ListProperty() { m_data = new ObservableCollection(); m_data.CollectionChanged += (s, e) => { if (CollectionChanged != null) CollectionChanged(s, e); }; } public string this[int index] { get { if (m_data.Count > index) { return m_data[index]; } else { return "Element not set for " + index.ToString(); } } set { if (m_data.Count > index) { m_data[index] = value; } else { m_data.Insert(index, value); } Console.WriteLine(value); } } public event NotifyCollectionChangedEventHandler CollectionChanged; } //--------------------------- public TestListProperty() { ListData = new ListProperty(); } }