Posted on Sunday 9 March 2008
Xaml is actually fairly easy to learn, I was trying to show someone how you accomplish a data binding between it and your code. Here are two examples of a bound text box:
<textbox width="100" maxlength="50" text="{Binding Path=BlockDesigner}">
</textbox> |
That is a simple binding. You can see the text being bound to a data variable called BlockDesigner.
<textbox width="45" maxlength="50" isreadonly="{Binding Path=IsChecked, ElementName=blockMonAuto}">
<textbox.text>
<binding path="MonLimit" notifyonvalidationerror="True">
<binding.validationrules>
<exceptionvalidationrule>
<rules:intrange min="0" max="2000">
</rules:intrange>
</exceptionvalidationrule>
</binding.validationrules>
</binding>
</textbox.text></textbox> |
This is a more complex binding, you can see the binding was created using a separate element. The reason for this is that it is using a validation rule to make sure that the text entered is an integer.
For all this, all you have to do in the code-behind is assign a data source.
BlockPanel.DataContext = MapStudio.Settings; |
In this case, the above text box is contained within a UserControl that I named BlockPanel. Because WPF looks for a data context at the element first, then checks all the parents above, it eventually finds it and uses it appropriately. This also saves you from having to assign the data context to every single textbox or element you want to use.
There is some pain involved, though, you can only bind to properties, and you have to design them a specific way so that the window knows that they have been updated. Overall, though, the extra step in the design (which is not at all a pain if you have, say, a snippet to do most of the work) is little enough to pay for the convenience.