WPF does not call TypeConverter when DependencyProperty is an interface

I am trying to create a TypeConverter that converts my custom type to ICommand if I bind it to Button Command.

Unfortunately, WPF does not call 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}" /> 

The converter will be called if I get attached to the content, for example:

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

Any ideas how I can get TypeConverter to work?

+6
source share
1 answer

You can do this if you create ITypeConverter . But you will have to use it explicitly, so write more xaml. On the other hand, sometimes being explicit is good. If you are trying to avoid declaring a converter in Resources , you can get from MarkupExtension . Thus, your converter will 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 will use it like:

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

Source: https://habr.com/ru/post/952059/


All Articles