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

本文关键字:创建 事件处理 程序 方式 编程 | 更新日期: 2023-09-27 18:12:24

我有一个组合框与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。

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

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);
. . .

你可以这样做:

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