質問

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}

OKをコンパイルしましたが、パスが内部の静的クラスに解決できないデータコンテキストであるクラス '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"

and

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 'One.Two.MetaData.Sizes' not found が発生します。 &quot; Blah&quot;よりも深いローカル名前空間を作成できません。 (とにかくVS2008によれば)

xmlns:local="clr-namespace:Blah"

and

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

1つが静的クラスではない場合、x:Staticでバインドすることはできません。内部クラスを使用する理由メタデータが2以外であり、Sizesがプロパティである場合、x:Staticを使用して簡単にアクセスできます。 この場合、既存のオブジェクトのみに型をバインドできません。ただし、1と2はオブジェクトではなくタイプです。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top