To bind or not to bind

In Programming on 24 July, 2008 at 7:00 pm

One feature of WPF is to bind a data providing class to a data receiving control, Microsoft decided to call it data-binding.  Data-binding is a strange topic for developer coming from C++, MFC background.  For them when you create a control, you will then needs to manually write code to add data to the control, there is no magic there.  In WPF, magic is created once you use data-binding, when the data providing class refresh with new data added, the control will automatically get updated to show all the new data items.  To accommodate developer who don’t understand much about data-binding, WPF with C# still provides the traditional way of adding data to a user control.  This is OK until you bring in the designer.

Let’s see an example.  For some reason WPF does not support checked list box, however customizing one from the vanilla ListBox is not that difficult.  I’ve seen developer recommending that since list box can take any control item, thus when you add item, just new a CheckBox item, add that to the ListBox and you have a checked list box.  This is correct as long as no visual changes is going to be done to the CheckBox item.  If you are going to change the square check box into something more fanciful and you want your designer to do that for you, you’re out of luck.  Since these check box items are created in the code and not on the XAML, designer can’t see it in the Microsoft Expression Blend and thus can’t change them.  Global styling you say?  What if in your UI there is another check box item and you don’t want them to look the same?

Data-binding can help you here.  Create a DataTemplate in your XAML file, bind it to the ItemTemplate of the ListBox control and bind the ItemSource to the data class which inherit from the ObservableCollection class.  Now you can customize the DataTemplate to consist of a check box and a text label and since this is created in a XAML file, designer can see it and thus can reshape to whatever she wants.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your 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: