C# Winforms - 不同控件具有相同属性名称的数据绑定

我在 Winforms 应用程序中使用数据绑定将 UI 元素连接到底层对象。我的 UI 中有几个ComboBoxes,每个都属于类的不同属性。以下面的简化代码为例:


实现的对象 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);

我的问题是,当我只想被调用时,当comboBox2.SelectedIndex更改时,两个Format处理程序都被调用,这是不希望的FormatForBinding2()。有没有办法解决这个问题?我是否对绑定有一些误解,因为我不能有多个具有相同属性名称和相同数据源的绑定,尽管控件不同?


HUH函数
浏览 258回答 1
1回答

HUWWW

我认为问题在于Format处理程序中执行的代码。该Format处理器应该只用来做什么它的名字所暗示-格式化值。正如我发现的那样,添加额外的逻辑会导致不良行为。需要考虑的一件事是,与Format处理程序一起,还包括所需 ComboBox的SelectedIndexChangedorSelectedValueChanged处理程序,并在其中执行其他逻辑。
打开App,查看更多内容
随时随地看视频慕课网APP