views:

584

answers:

2

Is there a way to do a comparison on object type for a trigger?

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

Background: I have a Toolbar and I want to Hide button's depending on what subclass is currently set to the selected item object.

Thanks

+2  A: 

Why not just use a converter that takes an object and returns a string of the object type?

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

and define the converter as:

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");
    }
}

You'll need to declare the static resource somewhere in your xaml:

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

Where 'convs' in this case is the namespace of where the converter is.

Hope this helps.

AndyG
+1 for the general idea, however the converter should return the Type object rather than its name...
Thomas Levesque
Would that work? Wouldn't the runtime be comparing something of type String to something of type Type? I know it handles converting/comparing most value types but not familiar with how it handles other Type comparisons.
AndyG
Yes, it would work, you just have to use the {x:Type} markup extension in the DataTrigger's value.
Thomas Levesque
+1  A: 

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

Thomas Levesque