bind checkbox to the value of the enum

If you want to create each CheckBox in XAML, you can assign the enum type to the Tag property.

Gets or sets an arbitrary object value that can be used to store custom information about this element.

I created an enum MyEnum with constants MyEnumConstant1 and so on, replace it with your own.

<CheckBox Content="My enum constant 1" Tag="{x:Static local:MyEnum.MyEnumConstant1}" Checked="EnumCheckBoxChecked"/>
<CheckBox Content="My enum constant 2" Tag="{x:Static local:MyEnum.MyEnumConstant2}" Checked="EnumCheckBoxChecked"/>
<!-- ...the other 38 check boxes. -->

Using the Checked event, you can get the Tag and add the enum value to EnumList or remove it. Since I do not know exactly what your EnumList is, I leave it like it is in this sample code.

private void EnumCheckBoxChecked(object sender, RoutedEventArgs e)
{
   var checkBox = (CheckBox)sender;
   var value= checkBox.Tag;

   if (checkBox.IsChecked.GetValueOrDefault())
   {
      EnumList.add(value);
   }
   else
   {
      EnumList.remove(value);
   }
}

The IsChecked property is a nullable bool. GetValueOrDefault will return false if it is null.

You can also do this in an MVVM compliant way by using view models and binding to a command.

<CheckBox Content="My enum value 1" Command="{Binding CheckedCommand}" CommandParameter="{x:Static local:MyEnum.MyEnumValue1}"/>

Here, you do not need the Tag property, as you pass the enum constant as command parameter.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top