【C#】在WPF中使用ComboBox绑定枚举类型

在WPF中使用ComboBox绑定枚举类型

一、实例

定义Enum:

cs 复制代码
internal enum StatusEnum
{
    [Description("待处理")]
    Pending,

    [Description("进行中")]
    InProgress,

    [Description("已完成")]
    Completed
}

定义扩展类,获取Description特性的内容:

cs 复制代码
internal static class EnumExtensions
{
    public static string GetDescription(this Enum value)
    {
        var field = value.GetType().GetField(value.ToString());
        var attribute = field?.GetCustomAttribute<DescriptionAttribute>();
        return attribute?.Description ?? value.ToString();
    }
}

值转换

cs 复制代码
internal class EnumToDescriptionConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is Enum enumValue)
        {
            return enumValue.GetDescription();
        }
        return value.ToString();
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return Enum.Parse(targetType, value.ToString());
    }
}

对象数据源

xml 复制代码
    <UserControl.Resources>
        <ObjectDataProvider x:Key="StatusEnumProvider" MethodName="GetValues" ObjectType="{x:Type sys:Enum}">
            <ObjectDataProvider.MethodParameters>
                <x:Type TypeName="local:StatusEnum" />
            </ObjectDataProvider.MethodParameters>
        </ObjectDataProvider>
    </UserControl.Resources>

ComboBox 绑定数据源

xml 复制代码
 <ComboBox ItemsSource="{Binding Source={StaticResource StatusEnumProvider}}"
       SelectedItem="{Binding SelectedStatus}"
           Width="140" FontSize="14"
           FontFamily="Microsoft Yahei UI"
           Cursor="Hand" >
     <ComboBox.ItemTemplate>
         <DataTemplate>
             <TextBlock Text="{Binding Converter={StaticResource EnumToDescriptionConverter}}"/>
         </DataTemplate>
     </ComboBox.ItemTemplate>
 </ComboBox>

SelectedStatus要在ViewModel里定义

二、ObjectDataProvider

ObjectDataProvider 类在XAML中创建对象并将其用作数据源。

xml 复制代码
  <ObjectDataProvider x:Key="StatusEnumProvider"
  	MethodName="GetValues" 
  	ObjectType="{x:Type sys:Enum}">
      <ObjectDataProvider.MethodParameters>
          <x:Type TypeName="local:StatusEnum" />
      </ObjectDataProvider.MethodParameters>
  </ObjectDataProvider>
  • ObjectType - 数据要返回的对象类型
  • MethodName - 要在 System.Enum类型上运行的方法名称
  • MethodParameters - 要提供给 MethodName 方法的值的集合

等效于以下代码:

cs 复制代码
 var itemsSource= System.Enum.GetValues(typeof(StatusEnum));
相关推荐
SomeOtherTime1 小时前
Rust所有权(AI回答)
开发语言·后端·rust
Easyhood1 小时前
Android 开发入门实践(十四):Compose 副作用入门与四个常用 API
android·开发语言·kotlin·android jetpack·compose
白杨尚青2 小时前
C++进阶篇(六):map 和 set 的模拟实现——用红黑树封装 mymap/myset(迭代器 + operator[])
开发语言·c++·迭代器·stl·set·map·红黑树
饮水桶_T5 小时前
JAVA IO流笔记
开发语言·数据结构·算法
Felven8 小时前
C. Brr Brrr Patapim
c语言·开发语言
路溪非溪9 小时前
python标准库使用总结
开发语言·python
SomeOtherTime11 小时前
Rust 面向对象介绍(AI回答)
开发语言·python·rust
zh_xuan11 小时前
kotlin常见面试题
开发语言·kotlin·面试题
草莓熊Lotso13 小时前
【C++ 基于微服务的即时通讯系统】文件存储子服务实战:UUID生成、文件IO封装与全接口单元测试
开发语言·网络·数据库·c++·微服务·架构·单元测试
huaqianzkh14 小时前
WinForm C#:循环修改控件UI闪烁卡顿?SuspendLayout / ResumeLayout 与 BeginUpdate 优化
开发语言·ui·c#