Transformers


A transformer allows you to convert a value from one form to another as it propagates to and from a data source to a target. You might use a transformer to convert a value from its internal representation to a unique displayed value. For example, you can use a transformer to display a negative floating-point number using red text and a positive number using black text. You can also display different icons for various credit-worthy ratings for a customer.

You can also use a transformer as a data type converter. For example, your source value could be a Point object, while the property to which you want to bind the value requires a Length instance.

A transformer also receives the culture information for the user interface as one of its parameters. You can use this information to tailor the presented user interface to the current culture of the user ”for example, you can provide different icons when running under different cultures.

The IDataTransformer Interface

A transformer is any object that implements the IDataTransformer interface. Here s the definition of the interface:

 interface IDataTransformer { 
object Transform (object o, DependencyID id, CultureInfo culture);
object InverseTransform (object o, PropertyInfo pInfo, CultureInfo culture);
}

A data binding calls the Transform method when propagating a source value to a target property. Parameter o is the source value, parameter id identifies the target property, and parameter culture identifies the culture for the transformation.

The data binding calls the InverseTransform method when propagating a changed target property value back to the source. In this case, parameter o is the changed target property s value and pInfo identifies the type to which to convert the value. As before, culture is the culture for the transformation.

Both methods allow you to return null to indicate that the binding should not propagate a value in the respective direction. Here is a simple transformer that returns a color based on an integer value:

 <SimpleText Text="*Bind(Path=Name)" Foreground="*Bind(Path=Age; Transformer=AgeToColorTransformer)"/> 

public class AgeToColorTransformer: IDataTransformer {
public object Transform (object o, DependencyID di, CultureInfo culture) {
int age = (int) o;
if (age < 0 age > 120) return Grey;
if (age <= 30) return Green;
if (age <= 70) return Gold;
if (age <= 120) return Red;
}
public object InverseTransform (object o, PropertyInfo i, CultureInfo c) {
return null;
}
}



Introducing Microsoft WinFX
Introducing WinFX(TM) The Application Programming Interface for the Next Generation of Microsoft Windows Code Name Longhorn (Pro Developer)
ISBN: 0735620857
EAN: 2147483647
Year: 2004
Pages: 83
Authors: Brent Rector

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net