Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 326
Jap Avatar asked Oct 04 '13 07:10

Jap


1 Answers

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);

        };
    }

}
like image 200
Ibrahim Najjar Avatar answered Nov 12 '22 07:11

Ibrahim Najjar