19

我正在尝试将 WPF 文本框的 Maxlength 属性绑定到类深处的已知常量。我正在使用 c#。

该类的结构与以下内容不太相似:

namespace Blah
{
    public partial class One
    {
        public partial class Two
        {
             public string MyBindingValue { get; set; }

             public static class MetaData
             {
                 public static class Sizes
                 {
                     public const int Length1 = 10;
                     public const int Length2 = 20;
                 }
             }
        }
    }
}

是的,它嵌套得很深,但不幸的是,在这种情况下,如果不需要大量的重写,我就无法移动很多东西。

我希望我能够将文本框 MaxLength 绑定到 Length1 或 Length2 值,但我无法让它工作。

我期望绑定类似于以下内容:

<Textbox Text="{Binding Path=MyBindingValue}" MaxLength="{Binding Path=Blah.One.Two.MetaData.Sizes.Length1}" />

任何帮助表示赞赏。

非常感谢

4

5 回答 5

41
MaxLength="{x:Static local:One+Two+MetaData+Sizes.Length1}"

期间参考属性。加号指的是内部类。

于 2008-10-24T10:48:29.400 回答
7

固定的!

最初我尝试这样做:

{Binding Path=MetaData+Sizes.Length1}

编译好的,但是绑定在运行时失败,尽管类'Two'是路径无法解析为内部静态类的数据上下文(我可以做类似的事情:{Binding Path={x:Static MetaData+Size .Length1}} ?)

我不得不稍微摆弄一下我的课程的布局,但现在绑定正在工作。

新的类结构:

namespace Blah
{
    public static class One
    {
        // This metadata class is moved outside of class 'Two', but in this instance
        // this doesn't matter as it relates to class 'One' more specifically than class 'Two'
        public static class MetaData
        {
            public static class Sizes
            {
                public static int Length1 { get { return 10; } }
                public static int Length2 { get { return 20; } }
            }
        }

        public partial class Two
        {
            public string MyBindingValue { get; set; }
        }
    }
}

那么我的绑定语句如下:

xmlns:local="clr-namespace:Blah"

MaxLength="{x:Static local:MetaData+Sizes.Length1}"

这似乎工作正常。我不确定是否需要将常量转换为属性,但这样做似乎没有任何害处。

谢谢你们每一个人的帮助!

于 2008-10-24T12:42:22.467 回答
0

尝试与 x:Static 绑定。将具有 Sizes 命名空间的 xmlns:local 命名空间添加到您的 xaml 标头,然后使用以下内容绑定:

{x:Static local:Sizes.Length1}
于 2008-10-24T10:17:50.633 回答
0

不幸的是,我得到了以下错误Type 'One.Two.MetaData.Sizes' not found。我无法创建比“Blah”更深的本地命名空间(无论如何根据 VS2008)

xmlns:local="clr-namespace:Blah"

MaxLength="{x:Static local:One.Two.MetaData.Sizes.Length1}"
于 2008-10-24T10:31:47.733 回答
0

如果 One 不是静态类,则不能使用 x:Static 绑定到它。为什么使用内部类?如果元数据不在两个范围内,并且 Sizes 是一个属性,您可以使用 x:Static 轻松访问它。在这种情况下,您不能绑定到类型,只能绑定到现有对象。但是 One 和 Two 是类型,而不是对象。

于 2008-10-24T10:39:55.330 回答