EvalBinding Examples

Databinding in WPF is very powerful for binding directly to your business objects or UI Model. One thing that is missing here and would be useful for other areas of WPF is a way of writing expressions. Without this you can end up creating properties that duplicate each other just so that you can create suitable Bindings. A company called IdentityMine sell a set of controls called Blendables. These include the EvalBinding control that allows you write JScript expressions in your XAML. We’ve used EvalBinding extensively in our code and it’s been great. It saves us a lot of time and makes the code more readable and maintainable.

But like the rest of XAML sometimes the syntax of the markup can be awkward and difficult to figure out the first time. The fact that EvalBindings are JScript expressions written inside Markup extensions in turn written in XML doubly complicates everything So here I will list some examples of using EvalBinding that I’ve come across.

In all examples the uiModel namespace is the namespace of the properties that I am binding to. In these cases it is in a different class library so is referenced at the top of the XAML as:

xmlns:uiModel=clr-namespace:SlowTrain.UIModel;assembly=UIModel

Here I bind the visibility of a control to the value of an enumeration in my Model. If the value of SelectedViewMode is ViewModeFull, then the control will be visible. Otherwise it will be hidden. The syntax is difficult as you need to include x:Static as well as references to your own namespace, but once you have the syntax figured out it works perfectly.

Visibility={blendables:EvalBinding [.SelectedViewMode] \=\= [{x:Static uiModel:TrackViewMode.Full}] ? [{x:Static Visibility.Visible}] : [{x:Static Visibility.Collapsed}]}

Here I bind the ToolTip property of a ToggleButton to an expression based on one of its own properties, very useful in this scenario.

<ToggleButton IsChecked={Binding Path=IsRepeatEnabled, Mode=TwoWay}ToolTip={blendables:EvalBinding [{Self}.IsChecked] ? \’Turn repeat off\’ : \’Turn repeat on\’ }/>

Technorati Tags:

Tags:

Comments are closed.