XAML : Binding textbox maxlength to Class constant

喜欢而已 提交于 2019-11-30 11:06:55
MaxLength="{x:Static local:One+Two+MetaData+Sizes.Length1}"

Periods reference properties. Plus signs refer to inner classes.

Fixed!

Initially I tried doing this:

{Binding Path=MetaData+Sizes.Length1}

which compiled ok, however the binding failed at runtime, despite the Class 'Two' being the datacontext the path couldn't resolve into the inner static classes (could I have done something like : {Binding Path={x:Static MetaData+Size.Length1}} ?)

I had to fiddle with the layout of my classes a little but the binding is now working.

New class structure:

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; }
        }
    }
}

Then my binding statement is as follows:

xmlns:local="clr-namespace:Blah"

and

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

Which appears to work ok. I'm not sure whether or not the constants needed to be converted into properties, but there doesn't appear to be any harm in doing so.

Thankyou everyone for your help!

try to bind with x:Static. add a xmlns:local namespace with the namespace of Sizes to your xaml header and then bind with something like this:

{x:Static local:Sizes.Length1}

Unfortunately, with the following I get the error Type 'One.Two.MetaData.Sizes' not found. I cannot create a local namespace deeper than "Blah" (well according to VS2008 anyway)

xmlns:local="clr-namespace:Blah"

and

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

if One is not a static class you cannot bind to it with x:Static. why using inner classes? if metadata is outside of two, and Sizes is a property, you can easily access it with x:Static. you cannot bind to types in this case, only to existing objects. but One and Two are types, not objects.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!