WPF Trigger Binding: what's the best way to bind an enum value to visiblity?

I have a user control ( NameField ). In it, I have a stack panel containing 3 grids: StandardView , FluidView , OtherView . In the code behind, I have a DependencyProperty named View type NameFieldView ( enum ). The listing contains STANDARD , FLUID , OTHER .

I think I should create a converter, but I'm not sure if this is necessary. I basically want to make the only visible grid the one that matches the enum value ... that is, if View = NameFieldView.STANDARD then the grid named StandardView visible, and the other two are not.

Also, I'm not sure if this should be part of Grid.Resources/Style or Grid.Triggers ?

+7
c # triggers styles wpf
source share
3 answers

Like a lot of WPF, it really depends on your taste. Here are a few options.

You can create three IValueConverter that convert the value of the View property into visibility (or use the enumeration name as the ConverterParameter parameter and create one converter).

You can create three new properties, called StandardViewIsVisible, FluidViewIsVible, and OtherViewIsVisible, which are updated when the View property changes. These properties will be visible. This is by far the more “MVVM” way of doing things, even if you are not using ViewModel.

You can use a DataTrigger that sets the appropriate Visible or Collapsed grid depending on the current value of the View property.

+7
source share

I use data triggers for this. It looks something like this:

 <Style TargetType="DockPanel" x:Key="ViewStyle1"> <Setter Property="Visibility" Value="Collapsed"/> <Style.Triggers> <DataTrigger Binding="{Binding ViewStyle}" Value="ViewStyle1"> <Setter Property="Visibility" Value="Visible"/> </DataTrigger> </Style.Triggers> </Style> 

Then I create a DockPanel for each view style, and whenever the ViewStyle property changes, the corresponding view is displayed.

+10
source share

I would create a converter. If you add a converter whenever you have a corresponding binding problem like this, you will slowly create a library of them for your application, which will make things a lot easier for you in the future. I would call it something like NameFieldViewToVisibilityConverter - it should have two methods:

 public Object Convert(Object value, Type TargetType, Object param, CultureInfo Culture); public Object ConvertBack(Object value, Type TargetType, Object param, CultureInfo Culture); 

Convert will have a NameFieldView parameter and return a visibility value. ConvertBack will have the Visibility parameter and returns a NameFieldView value.

The binding will look like this:

 <Grid Name="StandardView" Visibility="{Binding View, Converter={StaticResource NameFieldViewToVisibilityConverter}" /> 
+1
source share

All Articles