为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

C#
HUH函数 2021-10-24 16:55:43
我在 Winforms 应用程序中使用数据绑定将 UI 元素连接到底层对象。我的 UI 中有几个ComboBoxes,每个都属于类的不同属性。以下面的简化代码为例:实现的对象 INotifyPropertyChangeclass 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()。有没有办法解决这个问题?我是否对绑定有一些误解,因为我不能有多个具有相同属性名称和相同数据源的绑定,尽管控件不同?
查看完整描述

1 回答

?
HUWWW

TA贡献1874条经验 获得超12个赞

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


查看完整回答
反对 回复 2021-10-24
  • 1 回答
  • 0 关注
  • 257 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信