【问题标题】:Unable to find enum type for static reference in WPF无法在 WPF 中找到静态引用的枚举类型
【发布时间】:2011-08-06 07:21:58
【问题描述】:

我正在尝试将枚举绑定到 WPF 中的单选按钮(受​​ this answer 启发),但我无法找到转换器参数的枚举类型:

枚举定义如下

namespace Application.Models
{
    public class Enums
    {
        public enum MySelections { one, two ,three };

        public MySelections CurrentSelection;

        ...

    }
}

我现在正在尝试像这样绑定复选框(假设数据上下文是正确的并且实现了值转换器:)

<Window x:Class="Application.MainWindow"
        ....
        xnlns:models="clr-namespace:Application.Models" >

...
<RadioButton Content="One"
             IsChecked="{Binding Path=CurrentSelection, Converter={StaticResource EnumToBooleanConverter}, ConverterParameter={x:Static models:Enums.MySelections.one}}" />
...

问题出在{x:Static models:Enums.MySelections.one} 上,它不断抛出无法找到类型models:Enums.MySelections 的错误。

如何找到我的枚举类型?

【问题讨论】:

  • 如果将枚举定义向上移动到命名空间并从绑定中删除 Enum 类,它是否有效?

标签: wpf c#-4.0 .net-4.0 enums valueconverter


【解决方案1】:

你可以在你的班级之外声明它:

namespace Application.Models
{
    public enum MySelections { one, two, three };

    public  class Enums
    {
        public MySelections CurrentSelection;

然后这个 xaml 就可以工作了:

.... ConverterParameter={x:Static models:MySelections.one}

x:Static 标记具有固定语法:

{x:静态 前缀:typeName.staticMemberName}

【讨论】:

  • 就是这样,谢谢。所以只是澄清一下,这个枚举现在在哪里?命名空间的静态成员?
【解决方案2】:

使用“+”而不是“.”在 XAML 中获取嵌套类型:

{x:Static models:Enums+MySelections.one}

【讨论】:

  • 除非在 VS2010 中至少会导致设计器无法加载视图,因此您甚至无法看到您要设计的内容。
  • +1 - 适合我。但是,它似乎不适用于 x:Type。 x:Type 不支持这种语法吗? (例如 {x:Type models:Enums+MySelections})
  • 太棒了!这应该被标记为正确答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-04-26
  • 1970-01-01
  • 2010-10-14
  • 1970-01-01
  • 2023-03-24
  • 1970-01-01
  • 2017-08-17
相关资源
最近更新 更多