JD2022-TU1/main/tools/framework/JD.WPF/Converters/FlagsToBooleanConverter.cs

60 lines
2.8 KiB
C#

using System;
using System.Linq;
using System.Windows.Data;
namespace JD.WPF.Converters
{
/// <summary>
/// Converter from a Flags enum to a boolean value. This converter takes exactly two values.
/// The first value is the currently active flags.
/// The second value is the flag to check.
/// The two values must have the same type.
/// Use true as parameter to invert the result.
/// Note : This converter doesn't support conversion to source.
/// </summary>
public class FlagsToBooleanConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
bool inverted = false;
if(parameter != null)
inverted = parameter.Equals(true);
// TODO : Temporary for ConfigurePlus. Check for a better solution.
if (values[0] == System.Windows.DependencyProperty.UnsetValue)
{
Console.WriteLine("Data Binding Warning : FlagsToBooleanConverter received an unset dependency property. ");
return Binding.DoNothing;
}
if (values.Length != 2)
throw new ArgumentException("FlagsToBooleanConverter requires two values. First value must be the currently active flags. Second value must be the flag to check. ");
if (!values[0].GetType().IsEnum)
throw new ArgumentException("First value provided to FlagsToBooleanConverter is not an enum. ");
if (values[0].GetType().GetCustomAttributes(false).FirstOrDefault(attrib => attrib is FlagsAttribute) == null)
throw new ArgumentException("First value provided to FlagsToBooleanConverter doesn't have the [Flags] attribute. ");
if (!values[1].GetType().IsEnum)
throw new ArgumentException("Second value provided to FlagsToBooleanConverter is not an enum. ");
if (values[1].GetType().GetCustomAttributes(false).FirstOrDefault(attrib => attrib is FlagsAttribute) == null)
throw new ArgumentException("Second value provided to FlagsToBooleanConverter doesn't have the [Flags] attribute. ");
if (values[0].GetType() != values[1].GetType())
throw new ArgumentException("The two flags values provided doesn't have the same type. ");
int checkedFlags = (int)values[0];
int flagToCheck = (int)values[1];
bool returnValue = ((checkedFlags & flagToCheck) == flagToCheck);
return inverted ? !returnValue : returnValue;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotSupportedException("FlagsToBooleanConverter does not support conversions to source. ");
}
}
}