假设您有一个可观察的对象类型Foo集合,并且您有一个用户可以从中选择的自定义ListView.
绑定的数据对象:
// property with getter / setter / INotifyPropertyChanged
ObservableCollection<Foo> MyCollection;
Run Code Online (Sandbox Code Playgroud)
在XAML中:
<ListView ItemsSource={Binding MyCollection} />
Run Code Online (Sandbox Code Playgroud)
是否更适合绑定到XAML中的SelectedIndex并在数据对象中创建以下内容:
int SelectedIndex { get; set; } // also raising property changed notifications
Foo SelectedObject
{
get { return MyCollection[SelectedIndex]; }
}
Run Code Online (Sandbox Code Playgroud)
或者创建它并绑定到XAML中的SelectedItem:
Foo SelectedObject { get; set; } // also raising property changed notifications
Run Code Online (Sandbox Code Playgroud)
为什么?