我正在尝试创建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);
}
}
的Xaml:
<Button Content="Execute" Command="{Binding CustomObject}" />
如果我将绑定到以下内容,将调用
转换器。
<Button Content="{Binding CustomObject}" />
我是如何让TypeConverter工作的?
答案 0 :(得分:3)
如果您创建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}}" />