【问题标题】:Access constants from nested C# class in xamlxaml 中的常量
【发布时间】:2011-04-24 13:22:49
【问题描述】:

假设我有一个类定义如下:

namespace MyProject.MyConstants
{
    public class Constants
    {
        public class Group1Constants
        {
            public const string DoIt= "DoIt";
        }
    }
}

我正在尝试在我的 xaml 中使用来自单独项目的这个 const。我包含了命名空间:

xmlns:constants="clr-namespace:MyProject.MyConstants;assembly=MyProject.MyConstants"

我正在尝试按如下方式使用常量:

<MenuItem Header="{x:Static controls:Constants.Group1Constants.DoIt}">

虽然上面不会编译,但是说

Cannot find the type 'Constants.Group1Constants'. Note that type names are case sensitive.

我一定错过了一些简单的东西。我想要做的就是在我的 xaml 中使用不同项目中的类中的一些常量。

有什么建议吗?

【问题讨论】:

    标签: wpf xaml


    【解决方案1】:

    试试这个:

    <MenuItem Header="{x:Static constants:Constants+Group1Constants.DoIt}">
    

    我使用“+”而不是“。”引用嵌套类。不确定这样做是否会遇到问题。

    【讨论】:

    • 太棒了,解决了!我以前从未见过“+”语法。
    • wtf 是“+”语法吗?
    • 谢谢,WPF 的语法让我惊叹
    • 除非它是静态类或对象,否则我们无法访问属性,但我们如何能够访问 XAML 呢?
    【解决方案2】:

    对于 XAML 中的文本框标签文本字段常量,我使用:

    Text="{x:Static local:[myConstantNamesClass].[name of constant string in your constant class]}" 
    

    然后需要构建解决方案以使其可访问。

    (请注意,local: XAML 命名空间将设置为引用 XAML 文件最顶部的 Constants 类的 CLR 命名空间。)

    【讨论】:

      猜你喜欢
      • 2011-05-13
      • 1970-01-01
      • 2012-03-23
      • 2011-10-11
      • 1970-01-01
      • 2012-10-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多