为什么组合框在创建时将其项目增加一倍? [英] Why is the combobox doubling its items when being created?

查看:43
本文介绍了为什么组合框在创建时将其项目增加一倍?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在以编程方式创建一个组合框,如下所示:

I'm creating a combobox programmatically as follows:

var cbo = new ComboBox();
cbo.HandleCreated += (s, e) =>
{
    cbo.DataSource = mylist;
};

当我执行上述操作时,组合框会显示列表中包含的项的两倍。但是,当我执行以下操作时,组合框显示正确的项目数:

When I do the above, the combobox displays double the items contained in the list. However, when I do the following, the combobox displays the correct number of items:

var cbo = new ComboBox() {
    DataSource = mylist
};

为什么会这样?

推荐答案

原因



Reason


HandleCreated 仅引发一次。问题是另外一回事,这是因为 ComboBox 中实现了 OnHandleCreated 和数据绑定的方式。

The HandleCreated raises just once. the problem is something else, it's because of the way that OnHandleCreated and data-binding has implemented in ComboBox.

这是 ComboBox OnHandleCreated 方法c>有效:

This is how OnHandleCreated method of the ComboBox works:


  • 它首先引发 HandleCreated 事件。 (请记住, IsHandleCreated 在这一点上是正确的。)

  • 然后针对 Items 控件的集合,发送 CB_ADDSTRING
    本机消息将项目添加到本机组合框。

  • It first raise HandleCreated event. (Keep in mind, IsHandleCreated is true at this point.)
  • Then for each item in Items collection of the control, sends a CB_ADDSTRING native message to add the item to native combo box.

这是设置 DataSource 的工作方式:

  • For each item in DataSource, it first adds the item to Items collection, then checks if IsHandleCreated is true, sends a CB_ADDSTRING native message to add the item to native combo box.

因此,当您在 HandleCreated <中设置 DataSource 时/ code>事件,对于每个项目,它都会发送 CB_ADDSTRING 本机消息两次。

So when you set DataSource in HandleCreated event, for each item it sends CB_ADDSTRING native message twice.

这就是为什么您在下拉菜单中两次看到项目,同时 Items.Count 显示正确计数的原因。此外,如果您单击其他项目(项目的最后一半),则会收到索引超出范围的异常。

That's why you see items twice in the drop-down and at the same time Items.Count shows correct count. Also it you click on additional item (the last half of the items) you will receive an index out of range exception.

要解决此问题,可以使用以下任一视蛋白:

To solve the problem, you can use either of the following optoins:


  1. 您可以延迟通过使用 BeginInvoke

HandleCreated 事件代码>作为另一种选择,您可以依赖 VisibleChanged 事件。

As another option you can rely on VisibleChanged event.

选项1-HandleCreated + BeginInvoke

var mylist = Enumerable.Range(1, 5).ToList();
var myvalue = 2;
var cbo = new ComboBox();
cbo.HandleCreated += (obj, args) =>
{
    BeginInvoke(new Action(() =>
    {
        cbo.DataSource = mylist;
        cbo.SelectedIndex = mylist.IndexOf(myvalue);
    }));
};
this.Controls.Add(cbo);

选项2-VisibleChanged

var mylist = Enumerable.Range(1, 5).ToList();
var myvalue = 2;
var cbo = new ComboBox();
cbo.VisibleChanged+= (obj, args) =>
{
    cbo.DataSource = mylist;
    cbo.SelectedIndex = mylist.IndexOf(myvalue);
};
this.Controls.Add(cbo);

这篇关于为什么组合框在创建时将其项目增加一倍?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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