【问题标题】:XAML : Binding textbox maxlength to Class constantXAML:将文本框最大长度绑定到类常量
【发布时间】:2024-01-12 07:05:01
【问题描述】:

我正在尝试将 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}" />

感谢任何帮助。

非常感谢

【问题讨论】:

    标签: xaml binding textbox constants maxlength


    【解决方案1】:
    MaxLength="{x:Static local:One+Two+MetaData+Sizes.Length1}"
    

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

    【讨论】:

    • 这是有用的信息!但是我还没有足够的声望来点击它!
    • 对我也很有用。谢谢斯图史密斯
    【解决方案2】:

    已修复!

    最初我尝试这样做:

    {Binding Path=MetaData+Sizes.Length1}
    

    编译成功,但是绑定在运行时失败,尽管类“Two”是路径无法解析为内部静态类的数据上下文(我可以做类似的事情:{Binding Path={x:Static元数据+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】:

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

      {x:Static local:Sizes.Length1}
      

      【讨论】:

        【解决方案4】:

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

        xmlns:local="clr-namespace:Blah"
        

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

        【讨论】:

          【解决方案5】:

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

          【讨论】:

            最近更新 更多