【问题标题】:Binding to dictionary using enum as key使用枚举作为键绑定到字典
【发布时间】:2022-01-15 11:38:54
【问题描述】:

我在使用枚举作为 xaml 文件中的键绑定到字典属性时遇到了问题。

我有一个带有属性的 ViewModel

public Dictionary<EColor, MyDataStatus> StatusByColor {get; set;}

EColor 是枚举,MyDataStatus 是我自己的具有属性 Value 的类。

在视图中我正在尝试创建绑定

<TextBlock Text="{Binding StatusByColor[enum:EColor.eRed].Value}"/>

我得到一个绑定错误

BindingExpression path error: '[]' property not found on 'object' ''Dictionary`2 .....

但是,如果我像这样输入一个数字(而不是使用枚举):

<TextBlock Text="{Binding StatusByColor[0].Value}"/>

效果很好

我认为这可能是 xaml 中“包含”枚举的问题(它在其他程序集中定义)但下面几行我可以像这样将它用作 CommandParameter。

Text="{Binding Path=StatusByColor, Mode=OneWay,
               Converter={StaticResource statusByColorToDayElapsedConverter}, 
               ConverterParameter={x:Static enum:EPaintColor.eRed}}"

在这种情况下(使用转换器参数),甚至 IntelliSense 都会建议枚举的值。

这就是我在 xaml 中“包含”枚举的方式:

"xmlns:enum="clr-namespace:CommonTypes.Enums;assembly=CommonTypes""

【问题讨论】:

标签: wpf dictionary enums binding


【解决方案1】:

首先,给出我的答案,我已经验证过了。

<TextBlock Text="{Binding StatusByColor[eRed].Value}"/>

我使用示例尝试了您的代码,并获得了与您提到的相同的结果。 但是当我尝试这段代码时。

<TextBlock Text="{Binding StatusByColor[0].Value}"/>

我将索引从 0 更改为 999。我遇到了异常 “System.Collections.Generic.KeyNotFoundException” 所以我确认存在从 Int 到 Enum 的类型转换。 但是,只能转换 Int 吗?字符串呢? 是的!字符串也有效。 参考: WPF Binding to items within a dictionary by key?

【讨论】:

    猜你喜欢
    • 2019-06-29
    • 2012-09-23
    • 1970-01-01
    • 2014-12-23
    • 1970-01-01
    • 2011-08-10
    • 2018-10-30
    • 1970-01-01
    • 2016-12-12
    相关资源
    最近更新 更多