C# 基础(十)举例说明ObservableCollection(比如ListView绑定时更新集合时,只能用ObservableCollection)和List的区别,非常有用

参考:https://www.cnblogs.com/zyj649261718/p/8072679.html

一、ObservableCollection和List的区别

1)ObservableCollection比较简单,继承了Collection, INotifyCollectionChanged, INotifyPropertyChanged

  Collection:为泛型集合提供基类。

  INotifyCollectionChanged:将集合的动态更改通知给侦听器,例如,何时添加和移除项或者重置整个集合对象。

  INotifyPropertyChanged:向客户端发出某一属性值已更改的通知。

  所以再ObservableCollection这个类的方法,对数据的操作很少,重点放在了当自己本事变化的时候(不管是属性,还是集合)会调用发出通知的事件。(一般用于更新UI,

  当然也可以用于写其他的事情。这个以后会写)

2)List就比较多了,继承了IList, ICollection, IEnumerable, IList, ICollection, IEnumerable。

  IList:表示可按照索引单独访问的一组对象。

  ICollection:定义操作泛型集合的方法。

  IEnumerable:公开枚举器,该枚举器支持在指定类型的集合上进行简单迭代。

  IList:表示可按照索引单独访问的对象的非泛型集合。

  ICollection:定义所有非泛型集合的大小、枚举器和同步方法。

  IEnumerable:公开枚举器,该枚举器支持在非泛型集合上进行简单迭代。

二、举例:

1、举例1:

MainWindow.xaml:

<ListBox x:Name="listbind" Height="61" HorizontalAlignment="Left" Margin="146,12,0,0" VerticalAlignment="Top" Width="120" >  
            <ListBox.ItemTemplate>  
                <DataTemplate>  
                    <TextBlock Text="{Binding Name}" />  
                </DataTemplate>  
            </ListBox.ItemTemplate>  
        </ListBox>  
        <ListBox x:Name="observbind" Height="74" HorizontalAlignment="Left" Margin="146,111,0,0" VerticalAlignment="Top" Width="120" >  
            <ListBox.ItemTemplate>  
                <DataTemplate>  
                    <TextBlock Text="{Binding Name}" />  
                </DataTemplate>  
            </ListBox.ItemTemplate>  
        </ListBox>  
        <TextBlock Height="23" HorizontalAlignment="Left" Margin="38,58,0,0" Name="textBlock1" Text="List绑定数据" VerticalAlignment="Top" />  
        <TextBlock Height="44" HorizontalAlignment="Left" Margin="12,125,0,0" Name="textBlock2" Text="ObservableCollection绑定数据" VerticalAlignment="Top" Width="112" />  
        <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

Person.cs:

1 public class Person  
2     {  
3         public string Name { get; set; }  
4     }

MainWindow.xaml.cs:

private List<Person> person1 = new List<Person>();  
        private ObservableCollection<Person> person2 = new ObservableCollection<Person>();  
  
        public DemoTestDiff()  
        {  
            InitializeComponent();  
            person1.Add(new Person() { Name = "张三" });  
            person1.Add(new Person() { Name = "李四" });  
            listbind.ItemsSource = person1;  
            person2.Add(new Person() { Name = "张三" });  
            person2.Add(new Person() { Name = "李四" });  
            observbind.ItemsSource = person2;  
        }  
  
        private void button1_Click(object sender, RoutedEventArgs e)  
        {  
            person1.Add(new Person() { Name = "王五" });  
            person2.Add(new Person() { Name = "王五" });  
        }

 

 运行程序点击button按钮,然后只有ObservableCollection的有添加。

表示当集合对象的集合改变时,只有ObservableCollection会发出通知更新UI。

这只是他们两个区别之一。 

2、举例2

以下方法可以更新ListView的UI:

        private ObservableCollection<PreviewListModel> _previewList = new ObservableCollection<PreviewListModel>();

        /// <summary>
        /// 预览信息列表
        /// </summary>
        public ObservableCollection<PreviewListModel> PreviewList
        {
            get { return _previewList; }
            set { SetProperty(ref _previewList, value); }
            //set { _previewList = value; RaisePropertyChanged("PreviewList"); }
        }

三、 ObservableCollection和List的互相转换

https://www.cnblogs.com/warioland/archive/2011/11/08/2240858.html

从数据库检索的出来的集合是List<T>类型,我们需要把它转成ObservableCollection类型怎么办?如下方法:

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

数据库检索:

    public void AdvancedSearchFunc(AdvancedSearchNotification advancedSearchNotification)
        {
            try
            {
                KrayMobileDREntities dataBase = new KrayMobileDREntities();
                //每次使用前必须清零
                patientInfoHistroryModel.Clear();
                //先把数据库的数据提取出来,放到集合中。
                List<PatientInfo_Table> patientInfoList =
                    dataBase.PatientInfo_Table.Where(u => u.PatientKey.ToString().Equals(advancedSearchNotification.PatientInfo)
                                                        || u.PatientID.ToString().Equals(advancedSearchNotification.StudyID)
                                                        || u.PatientName.ToString().Equals(advancedSearchNotification.PatientName)
                                                        ).ToList();
                List<PatientStudy_Table> patientStudyList = dataBase.PatientStudy_Table.Where(u => u.PatientKey < 10).ToList();
                //按条件检索集合
                List<PatientInfoHistroryModel> list =
                                (from pI in patientInfoList
                                where (pI.PatientKey < 1000)
                                select new PatientInfoHistroryModel()
                                {
                                    PatientInfo = pI.PatientKey.ToString(),
                                    StudyID = pI.PatientID.ToString(),
                                    PatientName = pI.PatientName.ToString(),
                                    PatientSex = pI.PatientSex.ToString(),
                                    PatientAge = pI.PatientAge.ToString(),
                                    PatientBrith = pI.PatientBirthDate.ToString(),
                                    PatientHeight = pI.PatientHeight.ToString(),
                                    PatientWeight = pI.PatientWeight.ToString(),
                                    RecordSource = pI.PatientSource.ToString(),
                                    //StudyTime       = PS.StudyDatetime,
                                    //EquipmentType   = PS.StudyPhysician,
                                    //StudyPart       = PS.StudyType,
                                    //SequenceAmount  = PS.SeriesCount,
                                    StudyTime = pI.PatientAge.ToString(),
                                    EquipmentType = pI.PatientAge.ToString(),
                                    StudyPart = pI.HangFlag.ToString(),
                                    SequenceAmount = pI.HangFlag.ToString(),
                                    StudyStutas = pI.StudyCompleteFlag.ToString(),
                                    SuspendState = pI.HangFlag.ToString(),
                                    FilmPrint = pI.PrintFlag.ToString(),
                                }).ToList();
                patientInfoHistroryModel = list;
                dataBase.Dispose();                  
            }
            catch (Exception ex)
            {
                MessageBox.Show("病人历史记录信息表【高级查询】状态下,发生数据库错误。错误信息:--------------" + ex.ToString());
                LogHelper.Error("OperateDataSheetViewModel.cs::AdvancedSearchFunc()高级查询失败--" + ex.Message);
            }
        }

四、总结

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

2、List表示可通过索引访问的对象的强类型列表。提供用于对列表进行搜索、排序和操作的方法。(大部分操作用Linq,很强大也很方便。)

  • 0
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我爱AI

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值