Here is part 2 of Josh Twist's 10 part series on the reasons to consider WPF for your next desktop application, this part explores the topic of databinding.
Earlier I introduced a series of posts entitled 10 reasons to consider WPF for your next desktop application. If you haven't read the intro yet, better head on back and read it first.
At this year's ADC TechBriefing I gave a talk entitled "Real World Applications with WPF" and in it I introduced some of my 'laws of WPF', including the zeroth law:
"If you're not using databinding, you're probably doing something wrong"
I love the way you can bind pretty much anything to anything. For example,
In this first example I've created a collection of Book objects (an ObservableCollection<Book> to be exact). The book object looks like this:
Once we've created this collection (which we fudge manually in the Window's constructor) we simply set it to the DataContext of the window and start binding away.
First, we bind the ItemsSource of the ListBox on the left to the DataContext of the window <ListBox Name="_lstBooks" ItemsSource="{Binding}" />Then we bind the GroupBox's (the fieldset surrounding the textboxes) DataContext to the selected item of the listbox. Nice. <GroupBox Header="Book Details" DataContext="{Binding ElementName=_lstBooks, Path=SelectedItem}">Then we bind each TextBox to the relevant property. Very nice. <TextBox Text="{Binding Name}" /><TextBox Text="{Binding Author}" /><TextBox Text="{Binding CustomerRating}" />Note that, because our binding is two-way (the default) if you change the values in the textboxes these will be persisted in memory on the actual instance. So if you change to look at another book and come back, your change will still be there. All ready for you to save to the database when the user clicks save (if I'd have had the foresight to create a Save button, or even a database for that matter).
That's probably "binding to data 101" covered, albeit at breakneck pace. But what else can we do? You can do much more than just binding to boring data! How about binding a transform to a control?
You may have noticed in the example above that there's a zoom bar at the bottom left of the screen (you can see this better in the xbap). This slider will actually zoom in the form.
But how can I bind one thing (the Page's background color) to THREE controls? Easy, with a MultiValueConverter and MultiBinding. <Page.Background> <MultiBinding Converter="{StaticResource colorConv}"> <Binding ElementName="_sliderRed" Path="Value"/> <Binding ElementName="_sliderGreen" Path="Value"/> <Binding ElementName="_sliderBlue" Path="Value"/> </MultiBinding></Page.Background>Be sure to check out the full source to see how this is done in full (available at the end of the series).
* I should use the term "elements" instead of "controls" when talking about WPF but it helps the transition.
Originally Posted by Josh Twist on 12 Oct 2007 here.