【发布时间】:2011-08-18 13:58:26
【问题描述】:
我有一个带有 BindingSource 组件的 Winforms 应用程序,它的 DataSource 设置为我为自定义数据对象创建的 DataSource。表单上还有几个控件,它们绑定到通过 BindingSource 公开的对象的各种属性。其中许多控件是组合框,并且将显示带有支持枚举的值,因此我正在为这些控件设置 DataSource,如下所示:
comboBox1.DataSource = new BindingSource(Utility.ToList(typeof(DataObject.EnumValues)), null);
comboBox1.DisplayMember = "Value";
comboBox1.ValueMember = "Key";
这一切都运行良好,但我有两个组合框,我需要能够在运行时更改它们以显示其他值(使用不同的反向枚举)。在这两种情况下,我将在如下代码中创建初始绑定和数据源:
comboBox2.DataBindings.Add(new Binding("SelectedValue", this.bindingSource, "PropertyName1", true));
comboBox2.DataSource = new BindingSource(Utility.ToList(typeof(DataObject.FirstSetOfEnumValues)), null);
comboBox2.DisplayMember = "Value";
comboBox2.ValueMember = "Key";
...然后当我需要 comboBox2 绑定并显示不同的值时,我会这样做:
comboBox2.DataBindings.Clear();
comboBox2.DataBindings.Add(new Binding("SelectedValue", this.bindingSource, "PropertyName2", true));
comboBox2.DataSource = null;
comboBox2.DataSource = new BindingSource(Utility.ToList(typeof(DataObject.SecondSetOfEnumValues)), null);
comboBox2.DisplayMember = "Value";
comboBox2.ValueMember = "Key";
据我所知,这工作正常,但它很丑陋,并且有 得到 是一个更好的方法来做到这一点,对吧?如果你知道它是什么,我很想听听!非常感谢!
【问题讨论】:
标签: c# winforms data-binding