Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Trigger based on Object Type

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

like image 279
Exist Avatar asked Oct 30 '09 21:10

Exist


2 Answers

This is based on @AndyG's answer but is a bit safer because it's strongly typed.

Implement an IValueConverter named DataTypeConverter, which accepts an object and returns its Type (as a System.Type):

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

Change your DataTrigger to use the Converter, and set the value to the Type:

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

Declare DataTypeConverter in the resources:

<UserControl.Resources>     <v:DataTypeConverter x:Key="DataTypeConverter"></v:DataTypeConverter> </UserControl.Resources> 
like image 95
Greg Sansom Avatar answered Sep 28 '22 05:09

Greg Sansom


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.

like image 22
AndyG Avatar answered Sep 28 '22 06:09

AndyG