1

私はデータバインディングに不慣れで、今日、私が理解できない次の奇妙なことに遭遇しました。

2つのラベル(labelAとlabelB)と2つのボタン(buttonAとbuttonB)を持つフォームがあります。

フォームは、2つのプロパティ(CountAとCountB)を持つオブジェクト(「formState」と呼ばれる)をホストします。labelA.TextはformState.CountAにデータバインドされ、labelB.TextはformState.CountBにデータバインドされます。

buttonAが押されると、formStateはプロパティ名として「CountA」を使用してPropertyChangeイベントを発生させます。buttonBが押されると、プロパティ名として「CountB」を使用してformState.PropertyChangeが発生します。

buttonAが押されるとlabelAだけが更新され、buttonBが押されるとlabelBだけが更新されると思います。ただし、いずれかのボタンを押すと、両方のラベルが更新されます。CountAプロパティとCountBプロパティは、値が読み取られるたびにインクリメントしてカウンターを返すため、これを確認できます。以下のコード。

誰かがこの振る舞いについて説明がありますか?

public partial class Form1 : Form
{
    private FormState formState = new FormState();

    public Form1()
    {
        InitializeComponent();

        labelA.DataBindings.Add(
            new Binding("Text", formState, "CountA"));

        labelB.DataBindings.Add(
            new Binding("Text", formState, "CountB"));
    }

    private void buttonA_Click(object sender, EventArgs e)
    {
        formState.raisePropertyChangedEvent("CountA");
        // both labelA and labelB get updated - why not just labelA?
    }

    private void buttonB_Click(object sender, EventArgs e)
    {
        formState.raisePropertyChangedEvent("CountB");
        // both labelA and labelB get updated - why not just labelB?
    }

    public class FormState : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        private int countA = 0;
        private int countB = 0;

        public int CountA
        {
            get { return ++countA; }
        }

        public int CountB
        {
            get { return ++countB; }
        }

        public void raisePropertyChangedEvent(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
4

2 に答える 2

3

それは、観察可能なオブジェクトの単純な消費者である可能性があります。INotifyPropertyChangedObjects の単純なコンシューマーは、プロパティ名を無視して、全体を再評価するだけかもしれません。クラスは次のようになると想像できます。

class NaiveConsumer
{
   void Foo(INotifyPropertyChanged observable)
   {
       observable.PropertyChanged += PropertyChangedHandler;
   }

   void PropertyChangedHandler(object sender, PropertyChangedEventArgs e)
   {
      // Evaluate all properties, even though only 1 prop changed.
      this.NameTextBox.Text = observable.Name;
      this.AgeTextBox.Text = observable.Age;
   }
}
于 2009-11-13T02:19:11.430 に答える
1

クラスの責任は変更通知を提供することです-それをどのように処理するかを決定するのは消費者の責任です。変更されたプロパティのすべてのプロパティをチェックすることを選択した場合、それを行うことができます。

于 2009-11-13T02:25:39.177 に答える