regarding ObservableCollection in c#

此生再无相见时 提交于 2019-12-13 10:45:12

问题


i found a piece of code that use ObservableCollection but they can use list or any other collection related classes. can anyone tell me what is the benifit of using ObservableCollection.

ObservableCollection<Employee> empData = new ObservableCollection<Employee> 
        {
            new Employee{Name="Diptimaya Patra", Contact="0000", 
                EmailID="diptimaya.patra@some.com", Country="India"},
            new Employee{Name="Dhananjay Kumar", Contact="00020", 
                EmailID="dhananjay.kumar@some.com", Country="India"},
            new Employee{Name="David Paul", Contact="1230", 
                EmailID="david.paul@some.com", Country="India"},
            new Employee{Name="Christina Joy", Contact="1980", 
                EmailID="christina.joy@some.com", Country="UK"},
            new Employee{Name="Hiro Nakamura", Contact="0000", 
                EmailID="hiro.nakamura@some.com", Country="Japan"},
            new Employee{Name="Angela Patrelli", Contact="0000", 
                EmailID="angela.patrelli@some.com", Country="Japan"},
            new Employee{Name="Zoran White", Contact="0000", 
                EmailID="diptimaya.patra@some.com", Country="Scotland"},
        };

please discuss in detail. thanks


回答1:


ObservableCollection implements INotifyPropertyChanged. This interface exposes events that allow consumers of your collection to be notified when the contents of the collection change.

This is mainly used when binding in WPF, for example let's say we have an ObservableCollection<string>:

ObservableCollection<string> MyStrings
{
    get
    {
        // return a collection with some strings here
    }
}

and this control in XAML:

<ComboBox ItemsSource="{Binding MyStrings}" />

The ComboBox will show the strings inside your ObservableCollection. So far, this would have worked just fine with a List<string> as well. However, if you now add some strings to the collection, for example:

<Button Click="AddSomeStrings" Content="Click me!" />

private void AddSomeStrings(object sender, RoutedEventArgs e)
{
    this.MyStrings.Add("Additional string!");
}

you will see that the contents of the ComboBox will be immediately updated and the string will be added to the list of options. This is all accomplished using INotifyCollectionChanged.




回答2:


The benefit of ObservableCollection is that it raises the CollectionChanged event every time the collection is changed, and the PropertyChanged event every time one of the properties of the collection is changed.

In a similar way, if you want an object (which is not a collection) to raise an event every time one of its properties change, you should make it implement INotifyPropertyChanged.



来源:https://stackoverflow.com/questions/4851390/regarding-observablecollection-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!