我试图将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}" />

感谢任何帮助。

非常感谢

有帮助吗?

解决方案 2

固定!

最初我尝试过这样做:

{Binding Path=MetaData+Sizes.Length1}

编译好了,但是绑定在运行时失败了,尽管类'Two'是路径无法解析到内部静态类的datacontext(我可以做类似的事情:{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}"

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

谢谢大家的帮助!

其他提示

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

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

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

{x:Static local:Sizes.Length1}

不幸的是,有了以下内容,我收到错误 Type'Two.Two.MetaData.Sizes'not found 。我无法创建比“Blah”更深的本地命名空间。 (反正VS2008反正)

xmlns:local="clr-namespace:Blah"

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

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top