简体   繁体   中英

Binding BooleanToVisibilityConverter to an enum in a View Model

I a View Model, I have:

   public enum EventViewMode
   {
       View,
       Update,
       Insert
   }

Then, in the view some controls must be visible or not accordiong a value of EventViewMode .

For boolean values, I used BooleanToVisibilityConverter converter.

Is there a way to use an expression in the binding system to convert the enum value to a boolean expression.

I mean, something like:

<Button x:Name="btnSave"  
   Visibility="{Binding MyVariable == EventViewMode.View ,  Converter={StaticResource booleanToVisibilityConverter}}" />

Note that MyVariable == EventViewMode.View does not work, it is for showing what I want to reach.

No there isn't I'm afraid. Your options are

  • Use a value converter
  • Expose the property as a visbility instead of a EventViewMode
  • Use data triggers to set the desired property (in this case visibility) based on Enum values, for example

     <Button x:Name="btnSave" Visibility="{Binding MyVariable == EventViewMode.View , Converter={StaticResource booleanToVisibilityConverter}}"> <Button.Style> <Style TargetType={x:Type Button}> <Setter Property="Visibility" Value="Collapsed" /> <Style.Triggers> <DataTrigger Binding="{Binding MyVariable}" Value="View"> <Setter Property="Visibility" Value="Visible" /> </DataTrigger> </Style.Triggers> </Style> </Button.Style> </Button> 

You could simply expose a property in your view model:

public bool IsVisible { get { return MyVariable == EventViewMode.View; } }

Don't forget to raise property changed notifications for IsVisible when you change MyVariable.

If you don't want to pollute your view model, the next simplest option is to implement another value converter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM