Tuesday, July 19, 2011

Binding ObservableCollection to ListBox in WPF

Listbox is derived from ItemsControl class and has ItemSource property. ItemSource property can accept any collection which implements IEnumerable interface. In this post I am going to bind ObservableCollection<T> with Listbox.

<ListBox x:Name="PeopleList" ItemsSource="{Binding}"
        DisplayMemberPath="FirstName"
        IsSynchronizedWithCurrentItem="True"
        Margin="10" Height="110"/>

public partial class BindingCollection : Window
{
    public ObservableCollection<People> PeopleLists =
           new ObservableCollection<People>();
    public BindingCollection()
    {
        InitializeComponent();
        LoadPeopleList();
        this.DataContext = PeopleLists;
    }
    private void LoadPeopleList()
    {
        PeopleLists.Add(new People("Mitesh", "Sureja", 29));
        PeopleLists.Add(new People("Pritesh", "Parmar", 30));
        PeopleLists.Add(new People("Dharmesh", "Bheda", 32));
        PeopleLists.Add(new People("Jatin", "Mishra", 28));
        PeopleLists.Add(new People("Paresh", "Bijvani", 30));
    }
}
public class People
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
    public People(string firstName, string lastName, int age)
    {
        FirstName = firstName;
        LastName = lastName;
        Age = age;
    }
}












First I bound ItemSource property in XAML than i set DisplayMemberPath to FirstName it means Listbox should display only values of FirstName property available in Collection. In Code behind, i created one class called People and created one ObservableCollection of People class. I added few data to that collection and set window’s DataContext property to ObserableCollection.

I also set IsSynchronizedWithCurrentItem property to true. This property ensures that the selected item always correspond to the CurrentItem property in ItemCollection. For example, I have two listbox and both are bound with same itemsource property. Now if I change selected item in any of the listbox it will automatically change selection in other listbox if the IsSynchronizedWithCurrentItem property is set to true in both Listbox. Let’s have a look on below XAML snippet.

<ListBox x:Name="PeopleList" ItemsSource="{Binding}"
        DisplayMemberPath="FirstName"
        IsSynchronizedWithCurrentItem="True"
        Margin="10" Height="110"/>
<ListBox x:Name="PeopleList1" ItemsSource="{Binding}"
        DisplayMemberPath="FirstName"
        IsSynchronizedWithCurrentItem="True"
        Margin="10" Height="110"/>

1 comment:

  1. Thank you, this helped me a lot!
    Couldn't find the DisplayMemberPath property anywhere else!
    Kudos! :)

    ReplyDelete