Tuesday, June 16, 2009

This whimsical binding. TwoWay Binding to DataContext. Binding in WPF part 3.

I often use Binding to DataContext. It is one of the main advantage of WPF. In most case I set custom class inherit of DependencyObject (for support DependencyProperty) and I have some like next code:

<TextBlock Text="{Binding Path=Id}" />
<TextBlock Text="{Binding Path=Name}" />
<TextBlock Text="{Binding Path=Surname}"/>

But sometime I set a simple type for example string. For this case I can implement next Binding:

<TextBlock Text="{Binding}" />

Note: Pay attention, when we bind directly to DataContext I have written a short form (only 'binding' keyword).

But when I try to implement TwoWay Binding to DataContext. I have exception - "Two-way binding requires Path or XPath.". It cannot set a value from somewhere because it doesn't know where it came from. I can easy fix it. For example property IsChecked of CheckBox has request TwoWay Binding in metadata. For this case I have written next code:

<CheckBox IsChecked="{Binding Path=DataContext, RelativeSource={RelativeSource Self}}">

It is not so graceful, but it works.

No comments: