Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

XAML and Converters Chaining

DZone's Guide to

XAML and Converters Chaining

· Java Zone
Free Resource

Managing a MongoDB deployment? Take a load off and live migrate to MongoDB Atlas, the official automated service, with little to no downtime.

Converters are an essential building block in XAML interfaces with one simple task: converting values of one type to another. Since they have a input, usually a view model property, and an output, it would be wonderful if we could somehow chain them to create a new converter that processes all internal converters. Luckily, this is quite simple to do, but we do need to create a new converter which will hold other converters and whose implementation will iterate over nested converters. Full code can be found over at Github repository here, only interesting parts will be highlighted in this blog post.

Our combining converter class is also a converter itself, but it can contain other converters inside it:

[ContentProperty("Converters")]
public class ChainingConverter : IValueConverter
{
    public Collection<IValueConverter> Converters { get; set; }
}

Converter functions are trivially implemented and iteratively go through the converters list and apply the converter on the previous value.

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
    foreach (var converter in Converters)
    {
        value = converter.Convert(value, targetType, parameter, culture);
    }
 
    return value;
}

ConvertBack is implemented in the same fashion.

This allows us to create new converters in XAML with the following syntax:

<c:ChainingConverter x:Key="InvertedBoolToVisibilityConverter">
    <c:InvertBoolConveter />
    <c:BooleanToVisibilityConverter />
</c:ChainingConverter>

But what if we need to send parameters to some of the converters, how can we do that when the same parameter is used throughout the ChainingConverter implementation? To provide custom parameter for individual converters, we can create a wrapper converter around existing converter and specify parameter on that wrapper. Here is a skeleton for such wrapper converter, notice that the wrapper is also a converter:

[ContentProperty("Converter")]
public class ParameterizedConverterWrapper : DependencyObject, IValueConverter
{
    // IValueConverter Converter dependency property
    // object Parameter dependency property
    // object DefaultReturnValue dependency property
     
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (Converter != null)
            return Converter.Convert(value, targetType, Parameter ?? parameter, culture);
        return DefaultReturnValue;
    }
}

Converter wrappers allow us to create complex converters such as this one:

<c:ChainingConverter x:Key="EnumToStringConverter">
     
    <c:Wrapper Parameter="First">
        <!-- return value == parameter; -->
        <c:EnumToBool />
    </c:Wrapper>
 
    <c:InvertBool />
     
    <c:BooleanToObject
        TrueValue="Hello"
        FalseValue="World"
        />
     
</c:ChainingConverter>

The final converter should be self explanatory even though you probably haven’t seen these converters before. You can see that unlike other converters, the wrapper is a dependency object which allows us to use bindings on the Parameter property since it is in fact a dependency property. More complex converters should be created from ordinary converters whenever possible, especially when working with primitive types such as bool, string, enums and null values.

What’s next?

The last example looked like a small DSL embedded in XAML. We could create converters that simulate flow control or conditionals. We could even create converters that switch depending on the property before it, essentially coding logic inside such converters. Whether that is desirable is debatable, but it can be done.

The full code with sample application can be found at the following Github repository: MassivePixel/wp-common.

 

MongoDB Atlas is the easiest way to run the fastest-growing database for modern applications — no installation, setup, or configuration required. Easily live migrate an existing workload or start with 512MB of storage for free.

Topics:

Published at DZone with permission of Toni Petrina, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}