19 March 2018

XAML - markup extensions

Recently, I wanted to pass a boolean parameter to a value converter, but whatever you put there is passed as a string. That's when I discovered markup extensions. They allow you to pass a custom class with properties of any type to the value converter. This class is something like this:

sealed class BoolMarkupExtension : MarkupExtension
{
    public bool Value { get; set; }

    public BoolMarkupExtension() { }

    public BoolMarkupExtension(bool value)
    {
        Value = value;
    }

    public override object ProvideValue(IServiceProvider serviceProvider) => Value;
}

The value converter will receive what the ProvideValue method returns as parameter, so you can send the property or the class itself if it has multiple properties.

The value converter parameter can now be set to this class:

Visibility="{Binding IsPlaying, Converter={StaticResource BoolVisibilityConverter}, ConverterParameter={converters:BoolMarkup true}}"

No comments:

Post a Comment