简介:
ObservableCollection<T> 表示一个动态数据集合,它可在添加、删除项目或刷新整个列表时提供通知。
介绍:
该类是实现接口的数据集合的内置实现 INotifyCollectionChanged 。
[System.Serializable]
public class ObservableCollection<T> : System.Collections.ObjectModel.Collection<T>, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged
使用:
ObservableCollection和List对比,ObservableCollection具备通知功能。
public class PersonNP : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string name;
public string Name
{
get { return name; }
set { name = value; Notify(); }
}
private string id;
public string Id
{
get { return id; }
set { id = value; Notify(); }
}
private void Notify([CallerMemberName]string obj ="")
{
if (PropertyChanged != null)
{
this.PropertyChanged (this, new PropertyChangedEventArgs(obj));
}
}
}
public ObservableCollection<PersonNP> ocP;
public List<PersonNP> listP;
public MainWindow()
{
InitializeComponent();
ocP = new ObservableCollection<PersonNP>() {
new PersonNP(){Id = "1", Name="test1"},
new PersonNP(){Id = "2", Name="test2"},
};
listP = new List<PersonNP>()
{
new PersonNP(){Id = "1", Name="test1"},
new PersonNP(){Id = "2", Name="test2"},
};
listbx1.ItemsSource = ocP;
listbx1.DisplayMemberPath = "Name";
listbx1.SelectedValuePath = "Id";
listbx2.ItemsSource = listP;
listbx2.DisplayMemberPath = "Name";
listbx2.SelectedValuePath = "Id";
}
public void Button_Click(object sender, RoutedEventArgs e)
{
listP[0] = new PersonNP() { Name = "test1 change" };
ocP[0] = new PersonNP() { Name = "test1 change" };
}
<Grid>
<StackPanel>
<ListBox x:Name="listbx1"></ListBox>
<ListBox x:Name="listbx2"></ListBox>
<Button Click="Button_Click" Content="Change"></Button>
</StackPanel>
</Grid>