Files
qhmes/yy-admin-master/YY.Admin.Core/Converter/EnumToBoolConverter.cs

61 lines
2.4 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.Globalization;
using System.Windows.Data;
namespace YY.Admin.Core.Converter
{
/// <summary>
/// 将枚举值和 bool 互转,适用于 ToggleButton 或 RadioButton
/// </summary>
public class EnumToBoolConverter : IValueConverter
{
/// <summary>
/// 将枚举值转换为 bool
/// </summary>
/// <param name="value">绑定的枚举值</param>
/// <param name="targetType"></param>
/// <param name="parameter">ConverterParameter 指定要匹配的枚举值</param>
/// <param name="culture"></param>
/// <returns>匹配返回 true否则 false</returns>
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
string enumValue = value?.ToString() ?? string.Empty;
string targetValue = parameter?.ToString() ?? string.Empty;
return enumValue.Equals(targetValue, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// 将 bool 转回枚举值
/// </summary>
/// <param name="value">ToggleButton.IsChecked</param>
/// <param name="targetType"></param>
/// <param name="parameter">ConverterParameter 指定对应的枚举值</param>
/// <param name="culture"></param>
/// <returns>如果 true 返回枚举,否则返回 Binding.DoNothing</returns>
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is bool isChecked && isChecked && parameter != null)
{
// 判断 targetType 是否是 Nullable 类型
if (Nullable.GetUnderlyingType(targetType) != null)
{
// 获取 Nullable 的基础类型
Type underlyingType = Nullable.GetUnderlyingType(targetType)!;
// 确保基础类型是枚举类型
if (underlyingType?.IsEnum == true)
{
return Enum.Parse(underlyingType, parameter.ToString()!);
}
}
// 如果不是枚举类型或 Nullable 类型,返回 Binding.DoNothing
else if (targetType.IsEnum)
{
return Enum.Parse(targetType, parameter.ToString()!);
}
}
return Binding.DoNothing;
}
}
}