方法一
<ObjectDataProvider
x:Key="dateOfWeekProvider"
MethodName="GetValues"
ObjectType="{x:Type sys:Enum}">
<ObjectDataProvider.MethodParameters>
<x:Type TypeName="vm:DateOfWeek" />
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
<ComboBox ItemsSource="{Binding Source={StaticResource dateOfWeekProvider}}" SelectedItem="{Binding SelectedDate}" />
方法二
定义
public class EnumBindingSourceExtension : MarkupExtension
{
private Type? _enumType;
public Type? EnumType
{
get => _enumType;
set
{
if (value != _enumType)
{
if (value != null)
{
var enumType = Nullable.GetUnderlyingType(value) ?? value;
if (!enumType.IsEnum)
{
throw new ArgumentException("EnumType must be an Enum.");
}
}
_enumType = value;
}
}
}
public EnumBindingSourceExtension()
{
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
if (_enumType == null)
throw new InvalidOperationException("The EnumType must be set.");
var actualEnumType = Nullable.GetUnderlyingType(_enumType) ?? _enumType;
var enumValues = Enum.GetValues(actualEnumType);
if (actualEnumType == _enumType)
{
return enumValues;
}
var tempArray = Array.CreateInstance(actualEnumType, enumValues.Length + 1);
enumValues.CopyTo(tempArray, 1);
return tempArray;
}
}
具体使用方法
<Window.Resources>
<ResourceDictionary>
<com:EnumBindingSource x:Key="enumBindingSource" EnumType="vm:DateOfWeek" />
</ResourceDictionary>
</Window.Resources>
<StackPanel
HorizontalAlignment="Center"
VerticalAlignment="Center"
Orientation="Vertical">
<ComboBox ItemsSource="{Binding Source={StaticResource enumBindingSource}}" SelectedItem="{Binding SelectedDate}" />
<TextBox Text="{Binding SelectedDate, Converter={StaticResource enumConverter}}" />
<TextBox Text="{Binding RelativeSource={RelativeSource AncestorType=Window}, Path=ActualHeight, Mode=OneWay, StringFormat='Height:{0:F3}'}" />
</StackPanel>