【问题标题】:Reflect control changes to DataSource using BindgSource使用 BindgSource 将控件更改反映到 DataSource
【发布时间】:2016-03-14 05:45:25
【问题描述】:

我正在使用 WinFroms 并尝试使用 BindingSource 将控件(ComboBox)更改反映到 DataSource。其实我想看看在comboBox中选择了什么项目。

我的模型是:

public class Foo
{
    public string Name { get; set; }

    public override string ToString()
    {
        return Name;
    }
}

public class Bar
{
    public List<Foo> Foos { get; set; }
    public Foo SelectedFoo { get; set; }
}

绑定:

        List<Foo> lst = new List<Foo>();
        lst.Add(new Foo{Name="Name1"});
        lst.Add(new Foo{Name="Name2"});

        Bar bar = new Bar { Foos = lst };

        InitializeComponent();

        // bSource - is a BindingSource on the form
        this.bSource.DataSource = bar;
        // cbBinds - is a ComboBox
        this.cbBinds.DataSource = bar.Foos;
        this.cbBinds.DataBindings.Add(new Binding("SelectedItem", this.bSource, "Foos", true));

此代码有效,所有 Foo 都显示在 cbBinding 中。但我也想反映组合框中所选项目何时更改。所以我希望 Bar.SelectedFoo 等于 cbBinds.SelectedItem(不使用组合框的更改事件)。

我不知道该怎么做。有可能吗?

【问题讨论】:

    标签: c# winforms data-binding combobox bindingsource


    【解决方案1】:

    您的代码中的主要问题是您将数据绑定设置为列表的Foos 属性,而您应该将数据绑定设置为SelectedFoo

    当您使用以下代码设置数据绑定时:

    comboBox1.DataSource = List1;
    comboBox1.DataBindings.Add(new Binding("SelectedItem", Model1, "Property1", true));
    

    在第一行你说组合框显示List1的所有项目。

    在第二行中,您说将组合的SelectedItem 绑定到Model1.Property1,这意味着当您更改组合的选定项时,Model1.Property1 将设置为组合的选定项。

    所以你的代码应该是这样的:

    this.comboBox1.DataBindings.Add(new Binding("SelectedItem", bs, "SelectedFoo", true));
    

    注意

    阅读以上说明。现在您知道使用BindingSource 不是强制性的,您也可以这样编写代码:

    this.comboBox1.DataSource = bar.Foos;
    this.comboBox1.DataBindings.Add(new Binding("SelectedItem", bar, "SelectedFoo", true));
    

    【讨论】:

    • 效果很好,谢谢。一个小补充:需要调用 this.cbBinds.Select();因为如果您不更改 ComboBox SelectedFoo 属性的选定项,则会为空。
    • 事实上bar.SelectedFoo 应该为空,因为你没有给它赋值并且你不需要这样的combo.Select()。但是,如果您看到调用 combo.Select() 会有所不同,实际上它会将您的组合设置为活动控件,然后当您的控件失去焦点时,它会设置 bar.SelectedFoo 的值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-05
    相关资源
    最近更新 更多