【问题标题】:WinForms - changing the bindingsource/datasource of a control at runtime?WinForms - 在运行时更改控件的绑定源/数据源?
【发布时间】: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


    【解决方案1】:

    如果这是一个 Web 表单,我可能会建议将 ComboBox2 作为两个单独的 ComboBoxes 并隐藏/显示您需要的那个。虽然我很欣赏这对于 WinForm 项目来说并不是那么容易,除非您使用的是流动布局?

    您可以添加一个函数来根据您的枚举类型返回您的数据源...我认为您不需要在调用 Clear() 后重新设置 DisplayMember 和 ValueMember 属性(但我可能错了) .

    除此之外,我认为你不能再简化它了。虽然我很高兴听到有人有更好的解决方案:)

    【讨论】:

      【解决方案2】:

      您不需要将 ComboBoxes 绑定到 BindingSource 的新实例。

      将您的 ComboBox 绑定到它们各自的 BindingSource。这可以通过 Windows 窗体设计器完成,也可以在您自己的代码中手动完成。如果您在代码中执行此操作,请确保保留对 BindingSources 的引用。如果您使用设计器,则会为您添加一个成员到您的 Form 类中。

      那么当你想显示一组不同的值时,你需要做的就是改变BindingSources上的DataSource,ComboBoxes就会相应地更新。

      干杯

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-06-11
        • 2013-02-03
        • 2023-04-02
        • 1970-01-01
        • 1970-01-01
        • 2019-03-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多