Home C# ObservableCollection example

Tips and tricks

Site statistics

Members : 19
Content : 104
Content View Hits : 18417

Who's Online

We have 308 guests online
ObservableCollection example PDF Print E-mail
User Rating: / 0
PoorBest 
Articles - C#
Written by Dot4Pro   
Tuesday, 01 December 2009 14:18

ObservableCollection:

You have a collection object that holds the collection of data that needs to be displayed on UI. Whenever  you add /remove  data on the collection object, that needs to be updated to the UI immediately.
The collection must implment the interface INotifyCollectionChanged  to achive this.  The interface exposes the CollectionChanged event which should be raised whenever the collection changes.
WPF provides the ObservableCollection<T> class, which is the built in implmentation of the data collection that implments InotifyCollectionChanged interface.

Usage:

Bind the instance of  ObservableCollection<T> to the DataContext of the UI element(eg Listbox). When you add/remove objects to the instance, the data gets immediately updated on the UI.

Code Example:

Create wpf application on the visual studio 2008. Open the main form(window1 ) on desing mode and add DataGrid.  Add one button at the bottom of the window.
Open the Mainwindow in code view.
Create a Class called User  seems like bellow.

public class User : INotifyPropertyChanged
    {
        private string _userName;
        public User()
        {
            UserName = "New user";
        }
        public string UserName
        {
            get { return _userName; }
            set
            {
                _userName = value;
                FirePropertyChangedEvent("UserName");
            }

        }

        private string _firstName;
        public string FirstName
        {
            get { return _firstName; }
            set
            {
                _firstName = value;
                FirePropertyChangedEvent("FirstName");
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        private void FirePropertyChangedEvent(string propertyName)
        {
            if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }


 

At the top inside the Window1 Class create a instance of ObjservableCollection.
In the construction of Window1 set the DataContext of datagrid instance to the collection object.
 

public partial class Window1 : Window
    {
        private IList<User> users = new ObservableCollection<User>();
        public Window1()
        {
            InitializeComponent();
            dataGrid1.DataContext = users;
            users.Add(new User(){UserName = "Prem",FirstName = "Prem Bdr"});

        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            users.Add(new User());
        }
    }
 


Now open the  main window(where the datagrid is placed) in xaml view.
Add columns to the datagrid and set binding data as below.
     

   <my:DataGrid AutoGenerateColumns="False" ItemsSource="{Binding}" Margin="12,12,12,41" Name="dataGrid1">
            <my:DataGrid.Columns>
                <my:DataGridTextColumn    Header="User name" Binding="{Binding UserName}"  />
                <my:DataGridTextColumn Header="First Name" Binding="{Binding FirstName}" />
            </my:DataGrid.Columns>
        </my:DataGrid>
 


Run the example and see the effect. When you click Add button you can see new row added automatically on the DataGrid. Add more codes to edit/remove the collection object to see the output.

Something about InotifyPropertyChangedEvent

In the example you can see A User class is implmenting InotifyPropertyChangedEvent and fire PropertyChanged event whenever the property is set. This Interface triggers the UI components to update data whenever object is changed.
InotifyCollectionChanged only notifies when the collection is modified(Added/Deleted data from the collection).
 

 

Last Updated on Tuesday, 01 December 2009 14:47
 

Add comment


Security code
Refresh

feed-image Feed Entries