一、继承的类和接口,还有它们的方法不同
1)ObservableCollection比较简单,继承了Collection, INotifyCollectionChanged, INotifyPropertyChanged
Collection:为泛型集合提供基类。
INotifyCollectionChanged:将集合的动态更改通知给侦听器,例如,何时添加和移除项或者重置整个集合对象。
INotifyPropertyChanged:向客户端发出某一属性值已更改的通知。
所以再ObservableCollection这个类的方法,对数据的操作很少,重点放在了当自己本事变化的时候(不管是属性,还是集合)会调用发出通知的事件。(一般用于更新UI,
当然也可以用于写其他的事情。这个以后会写)
2)List就比较多了,继承了IList, ICollection, IEnumerable, IList, ICollection, IEnumerable。
IList:表示可按照索引单独访问的一组对象。
ICollection:定义操作泛型集合的方法。
IEnumerable:公开枚举器,该枚举器支持在指定类型的集合上进行简单迭代。
IList:表示可按照索引单独访问的对象的非泛型集合。
ICollection:定义所有非泛型集合的大小、枚举器和同步方法。
IEnumerable:公开枚举器,该枚举器支持在非泛型集合上进行简单迭代。
DEMO
1 <ListBox x:Name="listbind" Height="61" HorizontalAlignment="Left" Margin="146,12,0,0" VerticalAlignment="Top" Width="120" >
2 <ListBox.ItemTemplate>
3 <DataTemplate>
4 <TextBlock Text="{Binding Name}" />
5 </DataTemplate>
6 </ListBox.ItemTemplate>
7 </ListBox>
8 <ListBox x:Name="observbind" Height="74" HorizontalAlignment="Left" Margin="146,111,0,0" VerticalAlignment="Top" Width="120" >
9 <ListBox.ItemTemplate>
10 <DataTemplate>
11 <TextBlock Text="{Binding Name}" />
12 </DataTemplate>
13 </ListBox.ItemTemplate>
14 </ListBox>
15 <TextBlock Height="23" HorizontalAlignment="Left" Margin="38,58,0,0" Name="textBlock1" Text="List绑定数据" VerticalAlignment="Top" />
16 <TextBlock Height="44" HorizontalAlignment="Left" Margin="12,125,0,0" Name="textBlock2" Text="ObservableCollection绑定数据" VerticalAlignment="Top" Width="112" />
17 <Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="77,211,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
xaml页面很简单,托2个listbox分别用来绑定ObservableCollection和List
1 public class Person
2 {
3 public string Name { get; set; }
4 }
实体类:
1 private List<Person> person1 = new List<Person>();
2 private ObservableCollection<Person> person2 = new ObservableCollection<Person>();
3
4 public DemoTestDiff()
5 {
6 InitializeComponent();
7 person1.Add(new Person() { Name = "张三" });
8 person1.Add(new Person() { Name = "李四" });
9 listbind.ItemsSource = person1;
10 person2.Add(new Person() { Name = "张三" });
11 person2.Add(new Person() { Name = "李四" });
12 observbind.ItemsSource = person2;
13 }
14
15 private void button1_Click(object sender, RoutedEventArgs e)
16 {
17 person1.Add(new Person() { Name = "王五" });
18 person2.Add(new Person() { Name = "王五" });
19 }
运行程序点击button按钮,然后只有ObservableCollection的有添加。
表示当集合对象的集合改变时,只有ObservableCollection会发出通知更新UI。
这只是他们两个区别之一。
综上所述:
ObservableCollection表示一个动态数据集合,在添加项、移除项或刷新整个列表时,此集合将提供通知。
List表示可通过索引访问的对象的强类型列表。提供用于对列表进行搜索、排序和操作的方法。(大部分操作用Linq,很强大也很方便。)
