Binding to instance properties

source relationship [ignore]
Binding in WPF is a powerful
and useful way to populate
controls. You can bind to many
different types of data sources
in many different ways. One way
that I am very comfortable with
is using a normalized relation
database like SQL, pulling data
out and pushing it back in using
stored procedures, creating business
objects from that data, and then
binding properties on those classes
to controls. This is a more common
scenario in development than say,
binding to a flat xml file.


To bind directly to property on an instance of a class is simple,
although not very apparent. So lets set up an example:

source relationship

This example program displays a handful of cities and allows the user to select each city to see its population. To achieve this we set up the XAML like so...

source relationship

To bind to an instance, you will need the name of the instance. Our cities property is what we want to bind to and is located on our window class. So here I provide the window an ingenious name: "MyWindow". Now that the window is named, we indicate during the binding, the name of the instance that holds our Cities property. OK, cool, but why am I binding to the DockPanel? That makes no sense! Well, by binding to the DockPanel's DataContext I am saying that any element inside that DockPanel (no matter how nested it is) will all share the same source. So MyWindow's Cities property is now shared for all elements inside that DockPanel. Now to see the population of the selected item we must set the listbox's IsSynchronizedWithCurrentItem property equal to true. That enables the TextBlock that is bound to "population" to update to the selected city's population.

source relationship
And here is the stunning user interface!

Programming XAML

kick it on DotNetKicks.com

comments
1

Well I will be first one to write something in the your web site. I think your site is very informative. You did a great job. ! Keep up the hard work!

commentPosted by Daiane :: 12/15/2008 8:56:11 PM

Add a new comment



CAPTCHA image
Enter the code shown:
not case sensitive
refresh image