我正在尝试创建 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/