WPF

WPF ListBox Binding

Jose Leon
Author

Binding a ListBox to a collection is simple. You just need to declare the Binding element in the XAML markup to make the connection to the list of objects. This will allow the ListBox to automatically populate itself with the items.

Below you can find the XAML markup example:

An this is the C# code:

namespace WpfApplication8{    ///     /// Interaction logic for MainWindow.xaml    ///     public partial class MainWindow : Window    {        public MainWindow()        {            InitializeComponent();            List colors = new List();            colors.Add(new MyColor("Red"));            colors.Add(new MyColor("Green"));            colors.Add(new MyColor("Blue"));            ListBoxTest.ItemsSource = colors;        }    }    public class MyColor    {        public string Name { get; set; }        public MyColor(string n)        {            this.Name = n;        }    }}

In this sample we're binding the Name property of the MyColor class to the Text property of the TextBlock element. We're connecting both using the ItemsSource property of the ListBox object. This will automatically fill the ListBox

Binding to an ObservableCollection

Binding to an ObservableCollection will allow the ListBox to refresh itself anytime a change is made in any of the items on the List. This way, you don't need to tell the ListBox to look for the items again as the change will automatically trigger an event in the collection the the ListBox will catch and handle.

To do this, we just need to create the item that implements the INotifyPropertyChanged interface and handle the necessary events. Below, we've changed the MyColor class so it can support Observables:

public class MyColor : INotifyPropertyChanged    {        private string name;        public String Name        {            get { return name; }            set            {                if (name == value) return;                name = value;                RaisePropertyChanged("name");            }        }        public MyColor(string n)        {             this.Name = n;        }        public event PropertyChangedEventHandler PropertyChanged;        private void RaisePropertyChanged(string propName)        {            PropertyChangedEventHandler eh = PropertyChanged;            if (eh != null)            {                eh(this, new PropertyChangedEventArgs(propName));            }        }    }

When building the list, we don't use now a simple List object, we implement it using the ObservableCollection object as shown below:

ObservableCollection colors = new ObservableCollection();colors.Add(new MyColor("Red"));colors.Add(new MyColor("Green"));colors.Add(new MyColor("Blue"));ListBoxTest.ItemsSource = colors;

features

All posts

  • licensing
  • analytics

Easy .NET Protection

Purchase template