7

ボタンコマンドにバインドしている場合、カスタムタイプを ICommand に変換する TypeConverter を作成しようとしています。

残念ながら、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 を機能させる方法はありますか?

4

1 に答える 1

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}}" />
于 2013-08-19T19:41:59.860 に答える