You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WinUI 3用EnumValuesExtension绑定枚举到DataGridComboBoxColumn报错

问题说明

在WinUI 3(Windows App SDK 1.0.3版本)项目中,尝试使用EnumValuesExtensions将枚举类型绑定到DataGridComboBoxColumn时,运行抛出如下错误:

Markup extension could not provide value.(标记扩展无法提供值)

相关核心代码片段如下:

  • 页面XAML绑定代码
<controls:DataGrid AutoGenerateColumns="False"
                   ItemsSource="{x:Bind ViewModel.Devices, Mode=OneWay}">
   <controls:DataGrid.Columns>
      <controls:DataGridTextColumn Binding="{Binding Name}" Header="Name" />
      <controls:DataGridComboBoxColumn Binding="{Binding Type}" 
                                       ItemsSource="{ui:EnumValues Type=enums:DeviceType}"
                                       Header="Typ" />
   </controls:DataGrid.Columns>
</controls:DataGrid>
  • 待绑定枚举定义
public enum DeviceType
{
   [Description("Unbekannt")]
   Unknown = 0,
   [Description("Analogaktor")]
   AnalogActuator = 1,
   [Description("Analogaktor")]
   BinaryInput = 2,
}
  • 绑定用可观测实体类
public class ObservableDevice : ObservableValidator
{
   public DeviceType Type
   {
      get => ((Device)entity).Type;
      set => SetProperty(((Device)entity).Type, value, (Device)entity, (u, n) => u.Type = n);
   }

   public List<DeviceType> DeviceTypes
   {
      get => Enum.GetValues(typeof(DeviceType)).Cast<DeviceType>().ToList();
   }

   public ObservableDevice() : this(new Device())
   { }

   public ObservableDevice(Device device) : base(device)
   { }
}
错误原因

EnumValuesExtensions本身完全支持WinUI 3环境,报错核心原因是DataGridComboBoxColumn不属于页面可视化树的一部分,没有继承页面的XAML解析上下文,无法直接解析内联写在列属性上的标记扩展,因此无法获取枚举值集合。

解决方法

两种方案都可以解决问题,优先选择第一种:

  • 方案1:直接复用实体类已有属性
    你已经在ObservableDevice类中定义了返回所有枚举值的DeviceTypes属性,直接把列的ItemsSource绑定到该属性即可,不需要额外依赖标记扩展,稳定性最高:
    <controls:DataGridComboBoxColumn Binding="{Binding Type}" 
                                     ItemsSource="{Binding DeviceTypes}"
                                     Header="Typ" />
    
  • 方案2:将枚举集合声明为页面静态资源
    如果不想在实体类中存放枚举列表,可以先把EnumValuesExtensions的返回值定义为页面级资源,再通过StaticResource给列绑定,避开内联标记扩展的解析问题:
    1. 在页面资源块中添加枚举集合资源
    <Page.Resources>
        <ui:EnumValues x:Key="DeviceTypeCollection" Type="enums:DeviceType"/>
    </Page.Resources>
    
    1. 修改列的ItemsSource绑定为静态资源引用
    <controls:DataGridComboBoxColumn Binding="{Binding Type}" 
                                     ItemsSource="{StaticResource DeviceTypeCollection}"
                                     Header="Typ" />
    

内容的提问来源于stack exchange,提问作者Brecons

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.30 12:18:23