I am trying to create TypeConverter which will convert my custom type to ICommand if I am binding it to Button Command.
Unfortunetly WPF is not calling my converter.
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);
}
}
Xaml:
<Button Content="Execute" Command="{Binding CustomObject}" />
Converter will be invoked if I will bind to content like:
<Button Content="{Binding CustomObject}" />
Any ideas how I can get TypeConverter to work?
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}}" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With