代码之家  ›  专栏  ›  技术社区  ›  Thomas

XAML:将文本框最大长度绑定到类常量

  •  19
  • Thomas  · 技术社区  · 17 年前

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

    任何帮助都将不胜感激。

    非常感谢

    5 回复  |  直到 17 年前
        1
  •  41
  •   stusmith    17 年前
    MaxLength="{x:Static local:One+Two+MetaData+Sizes.Length1}"
    

    期间引用属性。加号表示内部阶级。

        2
  •  7
  •   Thomas    17 年前

    固定的!

    起初,我尝试这样做:

    {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}"
    

    这似乎工作得很好。我不确定是否需要将常量转换为属性,但这样做似乎没有什么坏处。

    谢谢大家的帮助!

        3
  •  0
  •   Joachim Kerschbaumer    17 年前

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

    {x:Static local:Sizes.Length1}
    
        4
  •  0
  •   Thomas    17 年前

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

    xmlns:local="clr-namespace:Blah"
    

    MaxLength="{x:Static local:One.Two.MetaData.Sizes.Length1}"
    
        5
  •  0
  •   Joachim Kerschbaumer    17 年前

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

    推荐文章