本文介绍了当 DependencyProperty 是接口时,WPF 不调用 TypeConverter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

Unfortunetly WPF is not calling my 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);
    }
}

XML:

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

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

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

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

有什么想法可以让 TypeConverter 工作吗?

Any ideas how I can get TypeConverter to work?

推荐答案

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

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}}" />

这篇关于当 DependencyProperty 是接口时,WPF 不调用 TypeConverter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 02:32