How do you apply a ValueConverter to a convention-based Caliburn.Micro binding Example?
Asked Answered
P

1

5

I have seen the following question: how-do-you-apply-a-valueconverter-to-a-convention-based-caliburn-micro-binding.

I couldn't post a comment on that topic, so I am posting my question here.

How to use the ConventionManager.ApplyValueConverter in Caliburn.Micro for value converters when using convention based binding ?

Could anyone write an example here?

Priapitis answered 4/10, 2013 at 7:4 Comment(0)
O
8

ApplyValueConverter is defined as a static Func<> delegate in the ConventionManager class.

In order to provide your own converter in convention-binding scenarios, you need to define your own Func<> in the Configure() method of your bootstrapper, something like this:

NOTE: I am assuming the conversion is from string to Opacity.

public class AppBootstrapper : Bootstrapper<ShellViewModel> {

    private static IValueConverter StringToOpacityConverter = new StringToOpacityConverter();

    public override void Configure() {

        var oldApplyConverterFunc = ConventionManager.ApplyValueConverter;

        ConventionManager.ApplyValueConverter = (binding, bindableProperty, property) => {
            if (bindableProperty == UIElement.Opacity && typeof(string).IsAssignableFrom(property.PropertyType))
            //                                ^^^^^^^           ^^^^^^
            //                             Property in XAML     Property in view-model
                binding.Converter = StringToOpacityConverter;
                //                  ^^^^^^^^^^^^^^^^^^^^^^^^^
                //                 Our converter used here.

            // else we use the default converter
            else
                oldApplyConverterFunc(binding, bindableProperty, property);

        };
    }

}
Organogenesis answered 4/10, 2013 at 9:43 Comment(3)
Wow, you know I've been using it for a fair while and I didn't even realise there was a convention for value converters! This saves a hell of a lot of typing!Felicitous
@Felicitous The funny thing is that I didn't know before the OP asked :). I am happy I learned that too.Organogenesis
It's the ONE thing I hate but never thought to check if there was support for.... (most) converters are so little bang for your buck when it comes to the amount of typing vs the payoff!Felicitous

© 2022 - 2024 — McMap. All rights reserved.