当DependencyProperty是接口时,WPF不调用TypeConverter

baa*_*mon 6 c# wpf

我正在尝试创建TypeConverter,如果我将它绑定到Button Command,它会将我的自定义类型转换为ICommand.

不幸的是WPF没有调用我的转换器.

转换器:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

XAML:

<Button  Content="Execute" Command="{Binding CustomObject}"  />
Run Code Online (Sandbox Code Playgroud)

如果我将绑定到以下内容,将调用转换器:

<Button  Content="{Binding CustomObject}"  />
Run Code Online (Sandbox Code Playgroud)

我有什么想法让TypeConverter工作?

Abe*_*cht 2

如果您创建一个ITypeConverter. 但是您必须显式地使用它,因此需要编写更多的 xaml。另一方面,有时明确是一件好事。如果您试图避免在 中声明转换器Resources,则可以从 派生MarkupExtension。所以你的转换器看起来像这样:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后你会这样使用它:

<Button Content="Execute" 
        Command="{Binding CustomObject, Converter={lcl:ToCommand}}" />
Run Code Online (Sandbox Code Playgroud)