Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF not calling TypeConverter when DependencyProperty is interface

Tags:

c#

wpf

I am trying to create TypeConverter which will convert my custom type to ICommand if I am binding it to Button Command.

Unfortunetly WPF is not calling my converter.

Converter:

public class CustomConverter : TypeConverter
{
    public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
    {
        if (destinationType == typeof(ICommand))
        {
            return true;
        }

        return base.CanConvertTo(context, destinationType);
    }

    public override object ConvertTo(
        ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
    {
        if (destinationType == typeof(ICommand))
        {
            return new DelegateCommand<object>(x => { });
        }

        return base.ConvertTo(context, culture, value, destinationType);
    }
}

Xaml:

<Button  Content="Execute" Command="{Binding CustomObject}"  />

Converter will be invoked if I will bind to content like:

<Button  Content="{Binding CustomObject}"  />

Any ideas how I can get TypeConverter to work?

like image 625
bartosz.lipinski Avatar asked Aug 19 '13 18:08

bartosz.lipinski


1 Answers

You can do it if you create an ITypeConverter. But you'll have to use it explicitly, so it is more xaml to write. On the other hand, sometimes being explicit is a good thing. If you are trying to avoid having to declare the converter in the Resources, you can derive from MarkupExtension. So your converter would look like this:

public class ToCommand : MarkupExtension, IValueConverter
{
    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        return this;
    }

    public object Convert(object value, 
                          Type targetType, 
                          object parameter, 
                          CultureInfo culture)
    {
        if (targetType != tyepof(ICommand))
            return Binding.DoNothing;

        return new DelegateCommand<object>(x => { });
    }

    public object ConvertBack(object value, 
                              Type targetType, 
                              object parameter, 
                              CultureInfo culture)
    {
        return Binding.DoNothing;
    }
}

And then you'd use it like:

<Button Content="Execute" 
        Command="{Binding CustomObject, Converter={lcl:ToCommand}}" />
like image 104
Abe Heidebrecht Avatar answered Oct 31 '22 07:10

Abe Heidebrecht