WPF: Observable collections for dynamic itemsource


ObservableColeection is ObjectModel collection which can be used to store and l list of objects in .Net. One of the notable feature of this collection is that unlike other collection it can be automatically update itemsources.

Observablecollection implements IObservable Interface

C# ObjectModel collection

Where to use Observable

Observable can be best fit where keep need to observe changing objects. The best example was a registration of student and throught the application you have to access the names, when ever a new registration occurs names should be available without any refresh in all other modules like, on studentmanagement,on fee collection,on attendance etc.

Observable collection aware change in items only when you do add new item, or delete / modify items in the collection.

Followiing example store and modify student scores and dynamically add to a datagrid.

The XAML

<Window x:Class="WpfApp2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp2"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="192*"/>
            <RowDefinition Height="227*"/>
        </Grid.RowDefinitions>
        <Button Click="Button_Click" Content="Add" HorizontalAlignment="Left" Height="64" Margin="26,28,0,0" VerticalAlignment="Top" Width="258"/>
        <Button Content="Clear" Click="Button_Click_1" HorizontalAlignment="Left" Height="72" Margin="26,110,0,0" VerticalAlignment="Top" Width="258"/>
        <Button Content="New Set" HorizontalAlignment="Left" Height="81" Margin="26,0,0,0" Grid.Row="1" VerticalAlignment="Top" Width="258" Click="Button_Click_3"/>
        <DataGrid ItemsSource="{Binding}" x:Name="resultgrid" HorizontalAlignment="Left" Height="245" Margin="344,28,0,0" Grid.RowSpan="2" VerticalAlignment="Top" Width="418"/>
    </Grid>
</Window>

The above code simply bind the grid with itemsource. Have a look at the c# source code.

ObserVableCollection : example

ViewClass

 class Result
    {
        public string sname { get; set; }
        public string grade { get; set; }
        public decimal mark { get; set; }
    }

We are creating a set of objects and create collection of objects and add and modify the collection.

Code behind the collection data

 public partial class MainWindow : Window
    {
        ObservableCollection<Result> studentset = new ObservableCollection<Result>();
        public MainWindow()
        {
            InitializeComponent();
            resultgrid.ItemsSource = studentset;            
            }
       private void Button_Click(object sender, RoutedEventArgs e)
        {

            Result mark;
            mark = new Result() { sname = "Abraham", grade = "A+", mark = 95 };
            studentset.Add(mark);
            mark = new Result() { sname = "Muhammed", grade = "B", mark = 95 };
            studentset.Add(mark);
            mark = new Result() { sname = "Nikhil", grade = "A", mark = 95 };
            studentset.Add(mark);            
        }
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            studentset.Clear();
        }
        private void Button_Click_3(object sender, RoutedEventArgs e)
        {
          Result  mark = new Result() { sname = "John", grade = "A", mark = 95 };
            studentset.Add(mark);
        }
    }

Each time an element to the collection were added , the itemsource is being updated and refreshed.

In my experience Observable collection is best suited for report objects, when ever a new item is added to the report collection your report is being updated, it is like you have a live reporting system.

Tip : You can create Method for adding only new items to the collection instead of removing all of them using Remove method of collection class.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.