您的位置:首页 > 其它

ObservableCollection<T>类

2016-03-15 19:45 281 查看
ObservableCollection<T>类

命名空间:system.Collections.ObjectModel

程序集:System(System.dll中)

该类表示一个动态数据集合,在添加项、移除项或刷新整个列表时,集合将提供通知。

以上是MSDN的介绍,该集合主要用在WPF的控件和数据源的绑定中,如:

xmal文件中,放置一个ListBox控件,名字叫做UserGroupListBox,ItemsSource设置如下:

<ListBox Name="UserGroupListBox" ItemsSource="{Binding Path=string,Mode=OneWay,UpdateSourceTrigger=PropertyChanged}" Height="214" HorizontalAlignment="Left" Margin="6,64,0,0" VerticalAlignment="Top" Width="173" Loaded="UserGroupListBox_Loaded" SelectionChanged="UserGroupListBox_SelectionChanged"
/>

对应的cs文件中:

ObservableCollection<string> strlist=new ObservableCollection<string>();

....

UserGroupListBox.ItemsSource=strlist;

这里要用ObservableCollection,这样在strlist发生变化时,UserGroupListBox的界面也会实时更新,而是用List<T>等其他容器是就没有这种效果。

值得注意的是这种变化只有在容器的元素数量发生变化时界面才会实时更新,若要做到容器内元素的属性发生变化界面同时更新的话,ObservableCollection<T>中的类型T必须从

INotifyPropertyChanged继承,并实现相应的接口,方法参考WPF中的Binding(一)

它们互换:

T tList = new List(tObjectStruct .ToList());  

ObservableCollection tObjectStruct  = new ObservableCollection(tList);  

 

都在构造函数中即可完成
也可以:
tList.ForEach(p => tObjectStruct.Add(t)); 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: