45

トリガーのオブジェクト タイプを比較する方法はありますか?

<DataTrigger Binding="{Binding SelectedItem}" Value="SelectedItem's Type">
</DataTrigger>

背景: ツールバーがあり、選択した項目オブジェクトに現在設定されているサブクラスに応じて、ボタンを非表示にしたいと考えています。

ありがとう

4

5 に答える 5

60

これは @AndyG の回答に基づいていますが、強く型付けされているため、少し安全です。

オブジェクトを受け取り、そのタイプを (System.Type として) 返す、DataTypeConverter という名前の IValueConverter を実装します。

public class DataTypeConverter:IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, 
      CultureInfo culture)
    {
        return value?.GetType() ?? Binding.DoNothing;
    }

    public object ConvertBack(object value, Type targetType, object parameter,
      CultureInfo culture)
    {
       throw new NotImplementedException();
    }
}

コンバーターを使用するように DataTrigger を変更し、値を Type に設定します。

<DataTrigger Binding="{Binding SelectedItem,  
      Converter={StaticResource DataTypeConverter}}" 
      Value="{x:Type local:MyType}">
...
</DataTrigger>

リソースで DataTypeConverter を宣言します。

<UserControl.Resources>
    <v:DataTypeConverter x:Key="DataTypeConverter"></v:DataTypeConverter>
</UserControl.Resources>
于 2011-02-11T04:40:48.870 に答える
38

オブジェクトを受け取り、オブジェクト型の文字列を返すコンバーターを使用しないのはなぜですか?

Binding="{Binding SelectedItem, Converter={StaticResource ObjectToTypeString}}"

コンバーターを次のように定義します。

public class ObjectToTypeStringConverter : IValueConverter
{
    public object Convert(
     object value, Type targetType,
     object parameter, System.Globalization.CultureInfo culture)
    {
        return value.GetType().Name;            
    }

    public object ConvertBack(
     object value, Type targetType,
     object parameter, System.Globalization.CultureInfo culture)
    {
        // I don't think you'll need this
        throw new Exception("Can't convert back");
    }
}

xaml のどこかで静的リソースを宣言する必要があります。

<Window.Resources>
    <convs:ObjectToTypeStringConverter x:Key="ObjectToTypeString" />
</Window.Resources>

この場合の「convs」は、コンバーターがある場所の名前空間です。

お役に立てれば。

于 2009-10-31T02:40:47.403 に答える
5

Using a converter as suggested by AndyG is a good option. Alternatively, you could also use a different DataTemplate for each target type. WPF will automatically pick the DataTemplate that matches the object type

于 2009-10-31T02:47:01.773 に答える
4

プロパティを追加して、「SelectedItem」に割り当てられた (ベース) タイプを変更する立場にある場合:

public Type Type => this.GetType();

次に、次のように xaml で DataTrigger を使用できます。

<DataTrigger Binding="{Binding SelectedItem.Type}" Value="{x:Type local:MyClass}">
</DataTrigger>

AndyG の良い答えと比較した利点は、XAML にタイプのマジック ストリングがなくても、すべてを安全にコンパイルできることです。欠点: モデルを変更する必要があります。これは常に可能であるとは限りません。

于 2019-01-31T10:15:50.587 に答える