1、先定义个枚举转换类
/// <summary>
/// 枚举转换
/// </summary>
public class EnumerationExtension : MarkupExtension
{
private Type _enumType;
/// <summary>
/// 枚举转换
/// </summary>
/// <param name="enumType">zhi</param>
public EnumerationExtension(Type enumType)
{
if (enumType == null)
throw new ArgumentNullException("enumType");
EnumType = enumType;
}
/// <summary>
/// enum
/// </summary>
public Type EnumType
{
get { return _enumType; }
private set
{
if (_enumType == value)
return;
var enumType = Nullable.GetUnderlyingType(value) ?? value;
if (enumType.IsEnum == false)
throw new ArgumentException("Type must be an Enum.");
_enumType = value;
}
}
/// <summary>
/// ProvideValue
/// </summary>
/// <param name="serviceProvider">1</param>
/// <returns>object</returns>
public override object ProvideValue(IServiceProvider serviceProvider)
{
var enumValues = Enum.GetValues(EnumType);
return (
from object enumValue in enumValues
select new EnumerationMember
{
Value = enumValue,
Description = GetDescription(enumValue)
}).ToArray();
}
private string GetDescription(object enumValue)
{
var descriptionAttribute = EnumType
.GetField(enumValue.ToString())
.GetCustomAttributes(typeof(DescriptionAttribute), false)
.FirstOrDefault() as DescriptionAttribute;
return descriptionAttribute != null
? descriptionAttribute.Description
: enumValue.ToString();
}
/// <summary>
/// EnumerationMember
/// </summary>
public class EnumerationMember
{
/// <summary>
/// Description
/// </summary>
public string Description { get; set; }
/// <summary>
/// Value
/// </summary>
public object Value { get; set; }
}
}
2、在wpf中使用
先引用上边的转换类文件
xmlns:comModel1="clr-namespace:NE.Model.Extend;assembly=NE.Model.Extend"
方法一:直接用
<ComboBox Grid.Row="2" Grid.Column="1" ItemsSource="{Binding Source={util:Enumeration {x:Type comModel:EGetWorkStepType}}}"
DisplayMemberPath="Description" SelectedValue="{Binding DataFilte_WorkTypeModel}" SelectedValuePath="Value"/>
方法二:DataGrid中使用
<DataGrid>
<DataGrid.Columns>
<DataGridTemplateColumn Header="方法" Width="10*" MinWidth="55" >
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox
Width="{Binding ElementName=Method, Path=ActualWidth}"
Margin="-10,0,0,0"
Padding="10,0,0,0"
HorizontalAlignment="Left"
VerticalAlignment="Center"
Background="Transparent"
BorderThickness="0"
ItemsSource="{Binding Source={util:Enumeration {x:Type comModel1:ERequestMethod}}}" DisplayMemberPath="Description"
SelectedValue="{Binding Method, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" SelectedValuePath="Value">
</ComboBox>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>