Skip to content

Instantly share code, notes, and snippets.

@Trinitek
Created January 24, 2020 07:58
Show Gist options
  • Select an option

  • Save Trinitek/99f88924a48033805962427fe23bfa8d to your computer and use it in GitHub Desktop.

Select an option

Save Trinitek/99f88924a48033805962427fe23bfa8d to your computer and use it in GitHub Desktop.
public class EnumToBooleanConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (Enum.IsDefined(value.GetType(), value) == false)
{
Debug.WriteLine("{0}: {1}: {2}: Value not defined in enum. Fallback to UnsetValue. {3}, {4}", nameof(EnumToBooleanConverter), GetHashCode(), nameof(Convert), value, value.GetType());
return DependencyProperty.UnsetValue;
}
if (parameter is string parameterString)
{
object parameterValue = Enum.Parse(value.GetType(), parameterString);
bool areEqual = parameterValue.Equals(value);
Debug.WriteLine("{0}: {1}: {2}: Value parsed. {3}, {4}, {5}", nameof(EnumToBooleanConverter), GetHashCode(), nameof(Convert), parameterValue, value.GetType(), areEqual);
return areEqual;
}
Debug.WriteLine("{0}: {1}: {2}: Fallback to UnsetValue. {3}, {4}", nameof(EnumToBooleanConverter), GetHashCode(), nameof(Convert), value, value.GetType());
return DependencyProperty.UnsetValue;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if (parameter is string parameterString)
{
object parsed = Enum.Parse(targetType, parameterString);
Debug.WriteLine("{0}: {1}: {2}: Value parsed. {3}, {4}, {5}", nameof(EnumToBooleanConverter), GetHashCode(), nameof(ConvertBack), parameterString, targetType, parsed);
return parsed;
}
Debug.WriteLine("{0}: {1}: {2}: Fallback to UnsetValue. {3}, {4}", nameof(EnumToBooleanConverter), GetHashCode(), nameof(ConvertBack), value, value.GetType());
return DependencyProperty.UnsetValue;
}
}
<ComboBox
Grid.Row="0"
Grid.Column="1"
VerticalAlignment="Center">
<ComboBoxItem IsSelected="{Binding Path=Quarter, Converter={StaticResource enumBooleanConverter}, ConverterParameter=First}">
First
</ComboBoxItem>
<ComboBoxItem IsSelected="{Binding Path=Quarter, Converter={StaticResource enumBooleanConverter}, ConverterParameter=Second}">
Second
</ComboBoxItem>
<ComboBoxItem IsSelected="{Binding Path=Quarter, Converter={StaticResource enumBooleanConverter}, ConverterParameter=Third}">
Third
</ComboBoxItem>
<ComboBoxItem IsSelected="{Binding Path=Quarter, Converter={StaticResource enumBooleanConverter}, ConverterParameter=Fourth}">
Fourth
</ComboBoxItem>
</ComboBox>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment