2013-08-19 21 views
6

ボタンコマンドにバインドする場合、私のカスタムタイプをICommandに変換するTypeConverterを作成しようとしています。DependencyPropertyがインターフェイスの場合、WPFが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を取得することができますどのように任意のアイデアは、 ?

+3

非常に興味深いです。私はインターフェイスであるタイプが問題であることを確認しました。テストコード:http://pastebin.com/EsMguMx5 - コンバーターは呼び出されませんが、依存関係プロパティー定義で 'IDestinationThing'を' DestinationThing'に変更するだけで作業が開始されます。 – nmclean

答えて

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}}" /> 
+0

私はコンバータを追加しないようにしたいと思います。 – baalazamon

+0

さて、 'ICommand'はいつでも実装できます(明示的に公開したくない場合は明示的に実装できます)。 WPFがあなたの 'TypeConverter'をインターフェイスで実行しない場合、あなたの唯一のオプションです。また、この質問への答えは、ここで何が起こっているのかを説明しているようです:http://stackoverflow.com/questions/17728436/why-are-icommand-properties-treated-specially-by-bindings –

+0

私はそれが嘘つきのためだと理解していますICommandの実装やコンバータの使用を必要としない回避策を見つけることを望んでいました。今はバインディングする前にオブジェクトを手で変換しています。 – baalazamon