以编程方式在C#中创建事件处理程序

时间:2016-10-10 10:41:05

标签: c# events event-handling

我有一个使用OwnerDrawMode实现的组合框如下:

this.comboBox8.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawVariable;
this.comboBox8.DrawItem += new DrawItemEventHandler(comboBox8_DrawItem);
this.comboBox8.MeasureItem += new    MeasureItemEventHandler(comboBox8_MeasureItem);

工作正常,但我现在想创建另外五个类似的组合框(9到13),它们基本相同,例如MeasureItems只是

private void comboBox8_MeasureItem(object sender, MeasureItemEventArgs e)
{
    e.ItemWidth = 44;
    e.ItemHeight = 15;
}

private void comboBox9_MeasureItem(object sender, MeasureItemEventArgs e)
{
    e.ItemWidth = 44;
    e.ItemHeight = 15;
}

只是重新输入它们似乎很简单但非常麻烦:-)

当我来到绘制项目时,它们包含的代码片段不会在不同的方框中发生变化(如上所述,但也有代码片段,其中逻辑没有改变,但名称从8改变)到9-13

private void comboBox8_DrawItem(object sender, DrawItemEventArgs e)
    {
        comboBox8.DataSource = c8_suits;

        if (e.Index >= 0) e.Graphics.DrawString(comboBox8.Items[e.Index].ToString(),
              e.Font, myBrush, e.Bounds, StringFormat.GenericDefault);
    }

TIA。

2 个答案:

答案 0 :(得分:3)

private void comboBox_MeasureItem(object sender, MeasureItemEventArgs e)
{
    e.ItemWidth = 44;
    e.ItemHeight = 15;
}

. . .

this.comboBox1.MeasureItem += new MeasureItemEventHandler(comboBox_MeasureItem);
this.comboBox2.MeasureItem += new MeasureItemEventHandler(comboBox_MeasureItem);
. . .

答案 1 :(得分:0)

你可以做这件事:

for (var i = 9; i <= 13; i++)
{
    var cb = new ComboBox();
    cb.MeasureItem += (s, e) =>
    {
        e.ItemWidth = 44;
        e.ItemHeight = 15;
    };
}