c# - 当 DependencyProperty 是接口(interface)时 WPF 不调用 TypeConverter

标签 c# wpf

我正在尝试创建 TypeConverter,如果我将它绑定(bind)到 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);
    }
}

Xaml:

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

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

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

关于如何让 TypeConverter 工作的任何想法?

最佳答案

如果您创建一个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;
    }
}

然后你会像这样使用它:

<Button Content="Execute" 
        Command="{Binding CustomObject, Converter={lcl:ToCommand}}" />

关于c# - 当 DependencyProperty 是接口(interface)时 WPF 不调用 TypeConverter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18320455/

相关文章:

c# - LoadIFilter() 在所有 PDF 上都失败(但 MS 的 filtdump.exe 没有。)

c# - 需要加速automapper ...做113个对象需要32秒

wpf - mvvm映射模型到数据

c# - 如何在非 UI 线程中使用 reg-free COM?

c# - 如何使用数据库中保存的颜色作为标签的背景色?

c# - FileUpload 服务器控件和 unicode 字符

c# - WPF - 删除启动后自动运行的应用程序

wpf - GridSplitter 的全局样式取决于其方向

c# - 如何在 WPF 中创建计时器?

c# - 自动选择组合框的第一项