學習WPF中綁定枚舉的方式
最近看到一篇介紹WPF綁定枚舉的好方法,查看地址:https://www.cnblogs.com/sesametech-netcore/p/13878443.html,這里記錄一下。
假定現在有個枚舉數據如下:
/// <summary>
/// 控制類型
/// </summary>
public enum CMDType
{
[Description("Ai巡檢")]
Ai,
[Description("心跳")]
Keeplive,
[Description("切源命令")]
Stream_cmd,
[Description("源狀態")]
Stream_state,
}
1、使用ObjectDataProvider
在xaml中引入命名空間System.
xmlns:sys="clr-namespace:System;assembly=mscorlib"
創建一個ObjectDataProvider資源,代碼如下:
<Window.Resources>
<ObjectDataProvider x:Key="DataEnum" MethodName="GetValues" ObjectType="{x:Type sys:Enum}">
<ObjectDataProvider.MethodParameters>
<x:Type TypeName="local:CMDType" />
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
</Window.Resources>
那么現在就可以使用數據綁定了。例如綁定到ComboBox:
<ComboBox ItemsSource="{Binding Source={StaticResource DataEnum}}" />
2、使用MarkupExtension
/// <summary>
/// 綁定枚舉
/// </summary>
public class EnumBindingSourceExtension : MarkupExtension
{
private Type enumType;
public Type EnumType
{
get => this.enumType;
set
{
if(value != this.enumType)
{
if(value != null)
{
var enumType = Nullable.GetUnderlyingType(value) ?? value;
if (!enumType.IsEnum)
{
throw new ArgumentException("類型不是枚舉");
}
}
this.enumType = value;
}
}
}
public EnumBindingSourceExtension()
{
}
public EnumBindingSourceExtension(Type enumType)
{
this.EnumType = enumType;
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
if(this.enumType == null)
{
throw new InvalidOperationException("類型為空了");
}
var actualEnumType = Nullable.GetUnderlyingType(this.enumType) ?? this.enumType;
var enumValues = Enum.GetValues(actualEnumType);
if(actualEnumType == this.enumType)
{
return enumValues;
}
var tempArray = Array.CreateInstance(actualEnumType, enumValues.Length + 1);
enumValues.CopyTo(tempArray, 1);
return tempArray;
}
}
使用Description屬性的值。
public class EnumDescriptionTypeConverter : EnumConverter
{
public EnumDescriptionTypeConverter(Type type)
:base(type)
{
}
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
if(destinationType == typeof(string))
{
if(value != null)
{
FieldInfo fi = value.GetType().GetField(value.ToString());
if(fi != null)
{
DescriptionAttribute attributes = (DescriptionAttribute)fi.GetCustomAttribute(typeof(DescriptionAttribute), false);
return attributes?.Description;
}
}
}
return string.Empty;
}
}
[TypeConverter(typeof(EnumDescriptionTypeConverter))]
/// <summary>
/// 控制類型
/// </summary>
public enum CMDType
{
[Description("Ai巡檢")]
Ai,
[Description("心跳")]
Keeplive,
[Description("切源命令")]
Stream_cmd,
[Description("源狀態")]
Stream_state,
}