WPF Bool to Enum converter

Here’s how to convert a bool to an generic enum in WPF:

XAML
—-

<ScrollViewer.HorizontalScrollBarVisibility>
    <Binding ElementName="ShowScrollers" Path="IsChecked" Converter="{StaticResource bte}" Mode="TwoWay">
        <Binding.ConverterParameter>
            <x:Array Type="ScrollBarVisibility">
                <ScrollBarVisibility>Hidden</ScrollBarVisibility>
                <ScrollBarVisibility>Auto</ScrollBarVisibility>
            </x:Array>
        </Binding.ConverterParameter>
    </Binding>
</ScrollViewer.HorizontalScrollBarVisibility>

C#

public class BooleanToEnumConverter : IValueConverter
{
  public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
  {
    var enumValues = parameter as Array;
 
    if ( parameter == null )
      return DependencyProperty.UnsetValue;
 
    bool balue = (bool)value;
    object ret = Enum.Parse( targetType, enumValues.GetValue(balue ? 1 : 0).ToString() );
    return ret;
  }
 
  public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
  {
    return null;
  }
}
This entry was posted in Coding, WPF and tagged , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *