侧边栏壁纸
  • 累计撰写 82 篇文章
  • 累计创建 11 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录
WPF

Combox绑定枚举

祈安千
2025-10-17 / 0 评论 / 0 点赞 / 10 阅读 / 0 字

方法一

<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>
0
博主关闭了所有页面的评论