C# 当DependencyProperty为接口时,WPF不调用TypeConverter
我正在尝试创建TypeConverter,如果我将自定义类型绑定到Button命令,它将把我的自定义类型转换为ICommand 不幸的是,WPF没有调用我的转换器 转换器:C# 当DependencyProperty为接口时,WPF不调用TypeConverter,c#,wpf,C#,Wpf,我正在尝试创建TypeConverter,如果我将自定义类型绑定到Button命令,它将把我的自定义类型转换为ICommand 不幸的是,WPF没有调用我的转换器 转换器: public class CustomConverter : TypeConverter { public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { if (destin
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);
}
}
公共类CustomConverter:TypeConverter
{
公共覆盖布尔CanConvertTo(ITypeDescriptorContext上下文,类型destinationType)
{
if(destinationType==typeof(ICommand))
{
返回true;
}
返回base.CanConvertTo(上下文,destinationType);
}
公共覆盖对象转换为(
ITypeDescriptorContext上下文,CultureInfo区域性,对象值,类型destinationType)
{
if(destinationType==typeof(ICommand))
{
返回新的DelegateCommand(x=>{});
}
返回base.ConvertTo(上下文、区域性、值、destinationType);
}
}
Xaml:
如果我将绑定到以下内容,则将调用转换器:
<Button Content="{Binding CustomObject}" />
你知道如何让TypeConverter工作吗?如果你创建了一个
itTypeConverter
,你就可以这样做。但是您必须显式地使用它,因此它更易于编写xaml。另一方面,有时候直言不讳是件好事。如果您试图避免在参考资料
中声明转换器,则可以从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;
}
}
公共类到命令:标记扩展,IValueConverter
{
公共覆盖对象ProviderValue(IServiceProvider服务提供程序)
{
归还这个;
}
公共对象转换(对象值,
类型targetType,
对象参数,
文化信息(文化)
{
if(targetType!=tyepof(ICommand))
不做任何事;
返回新的DelegateCommand(x=>{});
}
公共对象转换回(对象值,
类型targetType,
对象参数,
文化信息(文化)
{
不做任何事;
}
}
然后你会像这样使用它:
<Button Content="Execute"
Command="{Binding CustomObject, Converter={lcl:ToCommand}}" />
非常有趣。我已经确认,接口类型是问题所在。测试代码:-从不调用转换器,只需在依赖项属性定义中将IDestinationThing
更改为DestinationThing
,它就会开始工作。我希望避免添加转换器。好的,您可以始终实现ICommand
(如果不想公开它,请明确)。如果WPF不会为接口运行TypeConverter
,那么这些几乎是您唯一的选择。此外,这个问题的答案似乎描述了这里发生的事情:我理解这是由于InterfaceConverter的拙劣impl,希望找到一些不需要实现ICommand或使用转换器的解决方法。现在我正在绑定之前手动转换对象。不幸的是,除非MS在将来的更新中更改WPF的实现,否则您将无法使用TypeConverter
。因此,您必须使用当前的变通方法,IValueConverter
,或者使用其他一些非TypeConverter
方法。
<Button Content="Execute"
Command="{Binding CustomObject, Converter={lcl:ToCommand}}" />