Data binding with a ListBox and ComboBox in WPF

In the last post, we saw how to use data binding to a List to allow stepping through the elements of the List, displaying each item in separate TextBoxes. We also saw how a collection view provides an interface to the underlying List, and allows moving around the List as well as other operations like sorting and filtering.

However, when dealing with a list of objects, usually we would like a view that allows us to see several items in the list at the same time, and allows us to scroll through this display and select which item we want to deal with. To that end, we’ll have a look at how to bind a List to a ListBox and a ComboBox in WPF.

The program we use as illustration is an expanded version of the one from the previous post. The interface of the new program looks like this:

As before, we are looking at a list of books. Each book has an author, title, price and subject category. The available categories are shown in the ComboBox, while the titles of the books are displayed in a ListBox just above the buttons. Each category is represented by a unique integer code (so ‘physics’ has the code 2 in the picture). It is this numerical code that is stored in each Book object, so the textual representation of a given category is contained in a separate class called BookCategory. (Yes, I realize this example would be better done using a database, but for the purposes of illustrating data binding to lists, it serves its purpose.)

The buttons have the same functions as in the previous post (the First, Previous, Next and Last buttons move through the list of books, Add adds a new book to the list, Sort sorts the books by price and Cheap selects books with a price under 20.00. Nothing new here.

We’ve used data binding to keep the various parts of the interface synchronized. As we step through the list using one of the navigation buttons, the displays in the TextBoxes and ComboBox update to display the data in the current book, and the highlighted line in the ListBox also keeps in step with out current selection. If we select a book by clicking on a line in the ListBox, the rest of the display shows the data for that book. If we select a new category in the ComboBox, the Code box will update as well, and vice versa. (We haven’t put in any validation, so if you enter an invalid Code number, you won’t get an error message.)

The interface was built in Expression Blend as usual, so if you want to see the XAML for that, download the code (link at the end of the post) and have a look. We’ll look here at the code (all in C#) that does the binding between the lists and controls.

First, we’ll look at the classes that store the data that will be inserted into the lists. The Book class is slightly expanded from the previous post in order to accommodate the category code:

  class Book : INotifyPropertyChanged
  {
    public event PropertyChangedEventHandler PropertyChanged;
    protected void Notify(string propName)
    {
      if (this.PropertyChanged != null)
      {
        PropertyChanged(this, new PropertyChangedEventArgs(propName));
      }
    }

    string author;

    public string Author
    {
      get { return author; }
      set
      {
        if (author.Equals(value)) { return; }
        author = value;
        Notify("Author");
      }
    }

    string title;

    public string Title
    {
      get { return title; }
      set { if (title.Equals(value)) { return; }
        title = value;
        Notify("Title");
      }
    }

    decimal price;

    public decimal Price
    {
      get { return price; }
      set { if (price == value) { return; }
        price = value;
        Notify("Price");
      }
    }

    int categoryCode;

    public int CategoryCode
    {
      get { return categoryCode; }
      set { if (categoryCode == value) { return; }
        categoryCode = value;
        Notify("CategoryCode");
      }
    }

    public Book() { }
    public Book(string author, string title, decimal price, int code)
    {
      this.author = author;
      this.title = title;
      this.price = price;
      this.categoryCode = code;
    }
  }

Note, by the way, that the string returned in the Notify() call must match the name of the property in the code.

Next, we look at the BookCategory class:

  class BookCategory : INotifyPropertyChanged
  {
    public event PropertyChangedEventHandler PropertyChanged;
    protected void Notify(string propName)
    {
      if (this.PropertyChanged != null)
      {
        PropertyChanged(this, new PropertyChangedEventArgs(propName));
      }
    }

    int code;

    public int Code
    {
      get { return code; }
      set
      {
        code = value;
        Notify("Code");
      }
    }

    string category;

    public string Category
    {
      get { return category; }
      set
      {
        category = value;
        Notify("Category");
      }
    }

    public BookCategory(int code, string category)
    {
      Code = code;
      Category = category;
    }
  }

Again, no surprises here; it has the same form as the Book class.

Now we look at the binding code, contained in MainWindow.xaml.cs. The constructor is

    public MainWindow()
    {
      this.InitializeComponent();
      InitializeLibrary();
      InitializeCategoryList();
      UpdateButtonStates();
    }

After the standard InitializeComponent() call, we initialize the list of Books (the library) that is displayed in the ListBox and then the list of categories that is displayed in the ComboBox.

Here’s InitializeLibrary():

    ObservableCollection<Book> library;
    private void InitializeLibrary()
    {
      library = new ObservableCollection<Book>();
      library.Add(new Book("Feynman", "Feynman Lectures on Physics", BookPrice(), 2));
      library.Add(new Book("Asimov", "I, Robot", BookPrice(), 1));
      library.Add(new Book("Christie", "Death on the Nile", BookPrice(), 3));
      library.Add(new Book("Taylor", "From Sarajevo to Potsdam", BookPrice(), 4));
      LayoutRoot.DataContext = library;

      Binding listBoxBinding = new Binding();
      BindingOperations.SetBinding(booksListBox, ListBox.ItemsSourceProperty, listBoxBinding);
      booksListBox.DisplayMemberPath = "Title";
      booksListBox.SelectedValuePath = "CategoryCode";
      booksListBox.IsSynchronizedWithCurrentItem = true;
    }

We’re just hard-coding the first four books in the list. In more advanced code, you’d probably read them from a file and/or offer the user a way of entering the data in the interface (or, of course, read them from a database). Here we create a List of Books and set it as the data context.

Next we create a Binding and attach it to the list box (booksListBox is the ListBox that displays the books). The ItemsSourceProperty is set to this binding. Note that we don’t specify a Path for the binding itself. This causes the ListBox to bind to the entire data set in the data context. (Well, actually, it’s binding to the collection view that has been automatically wrapped around the List, as we saw in the previous post.) If we stopped at this point and ran the program, the ListBox would display a list of entires, each of which would say “ListBinding1.Book”. This is because, in the absence of any further instructions on how to display each element in the List, the ListBox calls the ToString() method of each object in the List. If no ToString() has been provided explicitly (we haven’t here), the default ToString() just prints out the data type of the object, which in this case is the Book class in the ListBinding1 namespace. In order to get something more informative to show up in the ListBox, we need to tell it which part of the Book object to display. That’s what the DisplayMemberPath is for. We set this to the name of the property of the Book that we want to show up; in this case, the Title. Note that DisplayMemberPath is a property of the ListBox and not of the binding. This can be a bit confusing, but if you think about it, it does make sense. The binding is concerned only with which element to display; the mechanics of what to display are handled by the UI control, in this case the ListBox.

The SelectedValuePath is a bit more subtle. List controls such as ListBoxes allow one property of the current item to be used for display, while reserving another property as the actual value of the item. The current item selected in a ListBox is the SelectedItem, and the value of this item is the SelectedValue. The SelectedValuePath tells the ListBox which property of the SelectedItem should be used for the SelectedValue. Thus SelectedValuePath is the name of a property and is not a value itself; the SelectedValue is the actual value of that property for the SelectedItem.

Finally we tell the ListBox to keep synchronized with the CurrentItem as specified in the collection view. If you don’t do this, the SelectedItem in the ListBox won’t change as you step through the Books in the collection view by using the navigation buttons.

If you ran the program at this point, you should see the titles displayed in the ListBox, and the highlighted item keep step with the CurrentItem as you use the buttons to move around the list. The ComboBox, however, will still be inert since we haven’t linked it into the program yet.

Now we look at the category list and how to bind it to the ComboBox. We use an ObservableCollection for this list as well, although in the current program there is no provision for adding or deleting categories, so we could have used an ordinary List with the same result. The code is:

    ObservableCollection<BookCategory> CategoryList;
    private void InitializeCategoryList()
    {
      CategoryList = new ObservableCollection<BookCategory>();
      CategoryList.Add(new BookCategory(1, "Science Fiction"));
      CategoryList.Add(new BookCategory(2, "Physics"));
      CategoryList.Add(new BookCategory(3, "Mystery"));
      CategoryList.Add(new BookCategory(4, "History"));
      Binding comboBinding = new Binding();
      comboBinding.Source = CategoryList;
      BindingOperations.SetBinding(categoryComboBox, ComboBox.ItemsSourceProperty, comboBinding);
      categoryComboBox.DisplayMemberPath = "Category";
      categoryComboBox.SelectedValuePath = "Code";

      Binding codeComboBinding = new Binding();
      codeComboBinding.Path = new PropertyPath("CategoryCode");
      BindingOperations.SetBinding(categoryComboBox, ComboBox.SelectedValueProperty, codeComboBinding);
    }

As with the book list, we are hard-coding a few categories for illustration; in real life you’d read these from a file or a database.

We begin by binding CategoryList to the combo box. Since CategoryList isn’t the data context, we need to specify it as the Source of the binding. As with the book list, we get the ComboBox to display the textual form of the category while using the numerical Code as its SelectedValue.

The semi-magical bit comes in the last 3 lines of code. Here we introduce a second binding for the ComboBox. This is a binding for the ComboBox’s SelectedValue, and we bind it to the CategoryCode property in the library (the list of Books). Note that we don’t specify a Source for this binding, so it will use the data context, which is the same library as the ListBox uses. By binding the ComboBox’s SelectedValue to the CategoryCode in the CurrentItem in the library, we synchronize the category displayed by the ComboBox to the category in the CurrentItem (the current Book being displayed). This means that if we change the category by typing a new number into the Code TextBox, then because that TextBox is bound to the CategoryCode in the Book, it will update that property. This in turn will cause the ComboBox’s SelectedValue to change. Then, due to the first binding between the CategoryList and the ComboBox, the new SelectedValue will be used to look up the corresponding DisplayMember, and the display of the ComboBox will be updated. The process also works in reverse: if you select a new category from the ComboBox, the same chain of events (in reverse) will cause the CategoryCode in the Book to change, which in turn will cause the Code TextBox to update.

There are only a couple of other minor changes that were made in this code compared to that in the previous post. The UpdateButtonStates() method has an extra line to ensure that the currently selected item in the ListBox is always visible, using the ScrollIntoView() method in ListBox:

    private void UpdateButtonStates()
    {
      CollectionView libraryView = GetLibraryView();
      previousButton.IsEnabled = libraryView.CurrentPosition > 0;
      nextButton.IsEnabled = libraryView.CurrentPosition < libraryView.Count - 1;
      booksListBox.ScrollIntoView(booksListBox.SelectedItem);
    }

Finally, the event handler for the Add button is modified to provide a category for a new book:

    private void addButton_Click(object sender, RoutedEventArgs e)
    {
      int newBookNum = library.Count + 1;
      library.Add(new Book("Author " + newBookNum, "Title " + newBookNum,
        BookPrice(), rand.Next(1, CategoryList.Count)));
      CollectionView libraryView = GetLibraryView();
      libraryView.MoveCurrentToLast();
      UpdateButtonStates();
    }

We generate the category randomly from those available in CategoryList.

Note that we didn’t need to change any of the logic for things like moving around the list, adding to the list, sorting or filtering. All of that is handled by the collection view, and the binding between the ListBox and ComboBox and the collection view works in exactly the same way as between the more cumbersome TextBox representation we used in the previous post.

Code available here.

Advertisements
Post a comment or leave a trackback: Trackback URL.

Comments

Trackbacks

  • By Using MySQL with WPF « Programming tutorials on April 12, 2012 at 4:58 PM

    […] so how do we use this to populate the ComboBox? Fortunately, we’ve already considered data binding with a ComboBox, so we can model our code along that example. We’ll do things a little differently here, […]

  • […] the collection of books. The data structures are similar to those that we used in discussing data binding to lists and combo boxes. The Book class is a bit simpler than it was […]

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: