Peter Morlion logo


WPF Databinding to Controls with ValueConverter

I’m a fan of the MVP design pattern, so databinding isn’t something I would use very often, but I have found a use for it in WPF. It is very easy to databind one Control to the other. This gives us some interesting possibilities.
For a standard example, check out this screencast. What I want to show here is how you can extend this with ValueConverters.
In a project of mine, I needed to show a control depending on the checked status of a RadioButton. More specifically, I needed to databind the Visibility of a Grid to the Checked property of a RadioButton. The problem is Visibility is an enumeration (Hidden, Visible, or Collapsed) and Checked is a Boolean, so this doesn’t databind just like that.
Luckily, there are ValueConverters: these just convert one value to another. There are a number of built-in ValueConverters, but you can also build your own. This is quite easy, but more on that later.

Focussing on my example with visibility, to databind with a ValueConverter in Blend, select the control you want to make (in)visible and click on the Advanced Property Options next to the Visibility Property:

Choose ‘Data Binding…’

Select the ‘Element Property’ tab at the top of the new window. You will see your controls in a treeview to the left. Select the control you want to databind to (in our example: a RadioButton). In the right part of the window, you’ll see the properties you can choose from. To get the IsChecked property, select ‘All Properties’ in the ‘Show’ listbox (bottom right). Select the IsChecked property:

Now all we need is a ValueConverter. Slide out the bottom part of this windows by clicking on the arrow. In het bottom left, you’ll see a ListBox for ValueConverter. If the BooleanToVisibilityConverter isn’t in the list yet, click on the ‘…’ button, and select it:

That’s all there’s to it. Repeat for other Controls and RadioButtons, and your GUI will change according to the selected RadioButtons.

Don’t use this for too many controls though, as they are still loaded, they’re just not visible. But it does show how WPF Controls can be databound to others.

Leave a Reply

Your email address will not be published. Required fields are marked *