WPF ObservableCollection<T> 

简介:

          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>

 

 

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值