Friday 20 May 2011

DynamicResource as a Binding using Styles

Suppose you've implemented an IValueConverter that you want to utilise on a DataTemplate. The problem is, this data template has been defined as a separate XAML template file, external from your VB code, to improve the extensibility of the program into the future. You don't want to have to dynamically generate the xaml to include the namespace reference to your assembly. What then?

The answer is: use WPF styles. This will allow you to programmatically bind parts of an XAML element, with the details of this determined via dynamic resources upon use of the template. This means you can create the binding and specify the IValue converter using code. Here's how you would do it in VB.net:


Dim sActivationStyle as Style=New Style()
Dim activationBinding as Binding=New Binding()
activationBinding.Path=new PropertyPath("activationDate")
activationBinding.Converter=new DateConverter()
sActivationStyle.Setters.Add(new Setter(TextBlock.TextProperty,activationBinding))


Here, DateConverter is your IConverter class you have created to format the DateTime value specified by the activationDate property of the relevant object. Then you use the binding like this:

<TextBlock Style="{DynamicResource activationDate}" DataContext="{Binding}" />

Voila! You now have a datatemplate, loaded at runtime, with a binding set as a dynamic resource.

No comments:

Post a Comment