(X) Hide this
    • Login
    • Join
      • Generate New Image
        By clicking 'Register' you accept the terms of use .
        Login with Facebook

Tip of the Day - Binding to a Collection

(0 votes)
0 comments   /   aggregated from Jesse Liberty - Silverlight Geek on Mar 16, 2008   /   original article
Categories:   General

Source Code - Same as Yesterday 

 

The Tip of the Day doesn't usually carry on a related series of postings, but data binding is so important that I'm making an exception this weekend. Yesterday we looked at laying out a form using a grid holding a DataGrid and a second grid to create a master detail relationship, with the end goal looking like this:

To populate the DataGrid that we've placed in the left column of the outer grid, we'll need a collection of business objects. To keep this simple, I've returned to the idea of a book class,

While it isn't strictly necessary for my Book class to implement INotifyPropertyChanged, it is convenient to have it do so, so that if the Book object is changed in the underlying data, the UI can be updated as well. Thus, each of the underlying private member fields  has a public property whose getter returns the private field and whose setter both sets the field and calls the Notify method to update the UI,

With the book class in place, it is easy to create a collection of Book objects based on the last few books I bought for my Kindle.  The steps are:

  1. Create a member variable to hold the collection
  2. Allocate memory for the collection
  3. Add objects to the collection
  4. Set the DataGrid to bind to properties of each individual object
  5. Set the collection as the ItemSource property of the DataGrid

Create a member variable to hold the collection

Allocate memory for the collection

Add objects to the collection

You can imagine that we would normally be retrieving these objects from a database, web server, or other common data source. Here we are hand coding to keep life simple.

Set the DataGrid to bind to properties of each individual object

In this small snippet you can see that we've created an instance of the DataGrid, named it Books, placed it in the grid, and told it not to auto generate its columns (we only want two columns, not all of the properties of the Book!).  We then manually create two text box columns, one for the Title and one for the ISBN.

Set the collection as the ItemSource property of the DataGrid

If you look closely at the line numbers you'll see that I cut out most of the "Add Book" calls to focus on the call to setting the ItemsSource on the DataGrid (look at line 23 in the previous image!).  By creating this binding, when the page loads the collection is bound to the data grid and the two properties from each book object are displayed automagically,

More soon on displaying the details and then moving beyond!


Subscribe

Comments

No comments

Add Comment

Login to comment:
  *      *       
Login with Facebook