共享ComboBox数据源 [英] Share ComboBox DataSource

查看:102
本文介绍了共享ComboBox数据源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以问为什么两个组合框触发对方,两者都有相同的值?
无法共享单个列表,并且有两个不同选定文本的组合框?

May I ask why does both comboboxes trigger each other such that both have same values? Can't I share a single list and have 2 comboboxes with different selected text?

private void Form1_Load(object sender, EventArgs e)
    {
        BindingList<string> list = new BindingList<string>();
        list.Add("A");
        list.Add("B");
        list.Add("C");
        list.Add("D");

        bind(cbo1, list);
        bind(cbo2, list);
    }

    private void bind(ComboBox combobox, BindingList<string> list)
    {
        // commented lines are in actual code,
        // but appears unimportant in this question
        //combobox.DropDownStyle = ComboBoxStyle.DropDown;
        //combobox.AutoCompleteSource = AutoCompleteSource.ListItems;
        //combobox.AutoCompleteMode = AutoCompleteMode.Suggest;
        combobox.DataSource = list;
        //combobox.Focus();
        //combobox.Text = string.Empty;
        //combobox.SelectedText = string.Empty;
    }

更新:
好​​了,现在我发现问题是DataSource由一些BindingContext和CurrencyManager管理以自动同步列表。但我觉得有人必须知道如何禁用这个行为。

UPDATE: Ok, now I found out the issue is that the DataSource is managed by some BindingContext and CurrencyManager to automatically synchronise the list. But I feel someone must know how to disable this behaviour.

我不想使用2个不同的列表,因为我想要能够在运行时修改这个单个列表并将更改反映到所有ComboBoxes。

I don't wish to use 2 different lists because I want to be able to modify this single list at runtime and have the changes be reflected on all ComboBoxes. Any method to achieve this would be greatly appreciated.

推荐答案

您可以像这样解决:

// combobox.DataSource = list;
var curr = new BindingSource(list, null);        
combobox.DataSource = curr;

有一个默认的BindingSource(Currencymanager)链接到每个表单,保持2 cbx同步。但我不知道什么确切的规则在这里。我甚至不确定上面是否是一个好主意或不。

There is a default BindingSource (Currencymanager) linked to each Form that was keeping the 2 cbx in sync. But I'm not sure what the exact rules are here. I'm not even sure if the above is a good idea or not.

对于小列表,我只需单独复制。

For small lists I would just make separate copies.

这篇关于共享ComboBox数据源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆