I am using data bindings in my Winforms application to connect the UI elements to an underlying object. My UI has several ComboBoxes
in it, each pertaining to a different property of the class. Take the following simplified code, for example:
INotifyPropertyChange
class MyObject : INotifyPropertyChange
{
// Custom logic in setters calls OnPropertyChanged
public int Property1 { get; set; }
public string Property2 { get; set; }
}
BindingSource MyDataSource = new BindingSource(this.components);
MyDataSource.Add(instanceOfMyObject);
Binding binding1 = new Binding("SelectedIndex", MyDataSource, "Property1",
false, DataSourceUpdateMode.OnPropertyChanged);
binding1.Format += FormatForBinding1();
comboBox1.DataBindings.Add(binding1);
Binding binding2 = new Binding("SelectedIndex", MyDataSource, "Property2"
false, DataSourceUpdateMode.OnPropertyChanged);
binding2.Format += FormatForBinding2();
comboBox2.DataBindings.Add(binding2);
My issue is that when comboBox2.SelectedIndex
changes, both Format
handlers are called, which is not desired, when I only want FormatForBinding2()
to be invoked. Is there a way to solve this? Am I misunderstanding something about bindings in that I cannot have multiple bindings with the same property name and the same data source, although the controls are different?
I think the issue was with the code being executed in the Format
handlers. The Format
handler should only be used to do what it's name implies -- format the value. Adding extra logic can lead to undesirable behavior, as I found out. One thing to consider is, along with the Format
handler, also including a SelectedIndexChanged
or SelectedValueChanged
handler for the desired ComboBox and doing the other logic in there.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.