Jump to content

Here 's another example that takes some more baby steps into WPF-style data binding As you 'v...


G+_Joe Maruschek
 Share

Recommended Posts

Here's another example that takes some more baby steps into WPF-style data binding.  As you've seen in my other two posts, data binding allows you to declare a connection between two elements, or an object and visual elements, and the data gets transferred automatically between the items and you don't have to write any code.

 

In this program I've re-used the Task class I had in the last example, but now I use the List collection class to create a list of tasks.  I use a for loop to make 50 task objects and add them to my list.  This simulates kind of what would happen in the "Model" part of a real application where you would either read a bunch of tasks in from a file, or get them from a web service like Lou's example. 

 

This time I set the DataContext property of the window to my list of tasks.  Over in the XAML, I've added a ListBox element.  The ListBox is one of several visual elements that are designed to work with collections of items.  It has a property called ItemsSource which is used for data binding.   In this case, I set that property to probably the shortest possible binding statement: {Binding}.  I'm telling it to bind to the entire list that I got set as the DataContext.  That's it!  Hit F5 to run.

 

Even though I never touched the ListBox in code, you can see it is filled with the names of all of the task objects I created.  I never even gave the ListBox a name, so I can't access it in code!

 

To make the listbox show all the names of the tasks, I had to add a short bit of code to the Task class I created.  I had to override the ToString() method, and I simply return the name of the task.  When the listbox fills, it calls ToString() on each item in the list to get the text it will show in its list.  It is a good idea to override ToString() in all of your custom classes because it is called by a lot of library functions.

 

With these baby steps we've taken, we're about at the level to understand what Lou was doing in his program.  Of course, there is always more to learn.  If you want to learn more, take a look at "Data Templates" in WPF.  They work with visual elements like the listbox and listview to customize how each item is displayed when you bind to a list.  I hoped you liked these simple examples.

http://www.joemaruschek.com/test/DataBindWithList.zip

Link to comment
Share on other sites

 Share

×
×
  • Create New...