38

プロパティにバインドできますが、別のプロパティ内のプロパティにはバインドできません。なぜだめですか?例えば

<Window DataContext="{Binding RelativeSource={RelativeSource Self}}"...>
...
    <!--Doesn't work-->
    <TextBox Text="{Binding Path=ParentProperty.ChildProperty,Mode=TwoWay}" 
             Width="30"/>

(注:マスターディテールなどを実行しようとはしていません。どちらのプロパティも標準のCLRプロパティです。)

更新:問題は、ParentPropertyが初期化されるXAMLのオブジェクトに依存していたことでした。残念ながら、そのオブジェクトはBindingよりもXAMLファイルで後で定義されたため、私のParentPropertyがBindingによって読み取られた時点ではオブジェクトはnullでした。XAMLファイルを再配置するとレイアウトが台無しになるため、私が考えることができる唯一の解決策は、コードビハインドでバインディングを定義することでした。

<TextBox x:Name="txt" Width="30"/>

// after calling InitializeComponent()
txt.SetBinding(TextBox.TextProperty, "ParentProperty.ChildProperty");
4

3 に答える 3

48

DataContextXAMLで設定することもできますTextBox(最適なソリューションかどうかはわかりませんが、少なくとも、実装する以外はcodeBehindで手動で何もする必要はありませんINotifyPropertyChanged)。TextBoxすでにDataContext(継承されているDataContext)場合は、次のようなコードを記述します。

<TextBox 
   DataContext="{Binding Path=ParentProperty}"
   Text="{Binding Path=ChildProperty, Mode=TwoWay}" 
   Width="30"/>

DataContextforのTextBox準備が整うまで、Textプロパティのバインディングは「確立」されないことに注意してください。FallbackValue='error'バインディングパラメータとして追加できます。これは、バインディングがOKかどうかを示すインジケーターのようなものになります。

于 2011-06-06T10:55:07.463 に答える
27

私が考えることができるのはParentProperty、が作成された後に変更されているというBindingことだけであり、変更通知をサポートしていません。チェーン内のすべてのプロパティは、変更通知をサポートする必要があります。これは、であるDependencyPropertyためか、を実装するためかは関係ありませんINotifyPropertyChanged

于 2009-06-10T22:45:47.333 に答える
4

ParentPropertyとクラスの両方がINotifyPropertyChangedを実装していますか?

    public class ParentProperty : INotifyPropertyChanged
    {
        private string m_ChildProperty;

        public string ChildProperty
        {
            get
            {
                return this.m_ChildProperty;
            }

            set
            {
                if (value != this.m_ChildProperty)
                {
                    this.m_ChildProperty = value;
                    NotifyPropertyChanged("ChildProperty");
                }
            }
        }

        #region INotifyPropertyChanged Members

        #endregion
    }

    public partial class TestClass : INotifyPropertyChanged
    {
        private ParentProperty m_ParentProperty;

        public ParentProperty ParentProperty
        {
            get
            {
                return this.m_ParentProperty;
            }

            set
            {
                if (value != this.m_ParentProperty)
                {
                    this.m_ParentProperty = value;
                    NotifyPropertyChanged("ParentProperty");
                }
            }
        }
}
    public TestClass()

    {
        InitializeComponent();
        DataContext = this;
        ParentProperty = new ParentProperty();
        ParentProperty.ChildProperty = new ChildProperty();

        #region INotifyPropertyChanged Members
        #endregion
    }
于 2009-06-11T00:58:11.497 に答える