Longhorn/XAML Property aliasing

Since so many people are talking about using the ContentPresenter to bind data via an alias, I figured it would be a good time to mention the IDataTransformer interface.

All you have to do is create a class to implement IDataTransformer, (and hit [tab] to insert the method stubs, if you're in Whidbey) and you're good to go with base functionality. 

Inside your bound property, just change the declaration a bit:

<SomeTag SomeProperty=“*Bind(Path=SomeDataBinding; Transformer=MyWordLengthTransformer)“ />

And inside your MyWordLengthTransformer : IDataTransformer class, you'll need to change the Transform method to suit your needs. In this rather primitive sample, you'll see that it transforms a string into a string length

public object Transform(object o, DependencyID di, CultureInfo culture)

{

string originalPropertyValue = (string)o;
return originalPropertyValue.Length;

}

For an added bonus of reuse, you can put it inside your <Window.Resources> or <Canvas.Resources> (etc.) tags as shown below:

<TransformerSource def:Name="MWLTransReference" TypeName="MyWordLengthTransformer"/>

and when you use the declaration in the XAML element, you'll use:

<SomeTag SomeProperty=“*Bind(Path=SomeDataBinding; Transformer={MWLTransReference})“ />


 

2 Comments

  • Can you expand this sample a bit? What code am I saving myself by writing a transformer? How and when is it called? Can you show a sample input and output?

  • I'll provide an expanded (working, compiling)sample shortly, but for now, I'll answer your questions here.



    1. By writing a transformer, you'll make the UIElements more able to accept other types of data than the default. Take for example the &quot;Text&quot; property of a Button control: normally, this will accept string values. You can make your control validate accepted values through a DataTransformer for one example. You could display different UI &quot;feels&quot; based on your data for another. Say you're making a Auction Application; you can bind the background of a Canvas to a transformed price. Your DataTransformer can make the lower priced items Green (or even better, the ones most matching your search criteria). I can think of many great uses for this!



    2. This is called from the XAML, when the code is databound. The bind statement itself transforms the data, so the control gets the output of the transformer.



    Sample coming soon (tomorrow, I promise)...

Comments have been disabled for this content.