私はデータバインディングに不慣れで、今日、私が理解できない次の奇妙なことに遭遇しました。
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));
}
}
}