I have two buttons and bind their property to two properties of a data object.
But every property is updated when I call PropertyChanged
of the data object.
public partial class Form1 : Form
{
private DataClass data = new DataClass();
public Form1()
{
InitializeComponent();
ButtonA.DataBindings.Add("Text", data, "DataA");
ButtonB.DataBindings.Add("Text", data, "DataB");
ButtonB.Click += new EventHandler(OnButtonBClicked);
}
private void OnButtonBClicked(object sender, EventArgs e)
{
data.DataA += "1";
data.DataB += "1";
data.Notify("DataB");
}
}
public class DataClass : INotifyPropertyChanged
{
public string DataA { get; set; }
public string DataB { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
public DataClass() {}
public void Notify(string property_name)
{
PropertyChanged(this, new PropertyChangedEventArgs(property_name));
}
}
When I press
ButtonB
(which means I callPropertyChanged(this, new PropertyChangedEventArgs("DataB"))
), bothButtonA
andButtonB
show new text.If I call
PropertyChanged(this, new PropertyChangedEventArgs("DataA"))
, both buttons are updated.If I don't change value of
DataA
/DataB
and just callPropertyChanged(this, new PropertyChangedEventArgs("DataB"))
, still both buttons are updated (can be noticed by breakpoint debugging).If I call
PropertyChanged(this, new PropertyChangedEventArgs("QQQ"))
, then no button is updated.
PropertyChangedEventArgs
has a property named propertyName
, I thought it's used to specify one property to notify but it doesn't.
In my real code, DataB
changes much more frequently than DataA
. I don't want to update ButtonA
each time DataB
is changed, it takes too much time.
Question: why would this happen? When a data source property is changed, how can I only update properties really connected to it?
(All code is .Net Framework 4.7.1 on Windows.)
@Jimi's method works.Simple and effective.I put each property in a shell class and bind data to the shell:
But in this way I must use
DataA.Content+="1"
instead ofDataA+="1"
every where.I decide to use a base class to create all shells.But my real
DataClass
must inherit from other class and C# don't support multi-inherit.So I have to use a extension class.Then bind it like
And notify like
It's kinda complex but works well.