【问题标题】:Programmatically creating event handlers in C#在 C# 中以编程方式创建事件处理程序
【发布时间】:2016-10-10 19:10:59
【问题描述】:

我有一个按如下方式实现 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;
}

等等

只是重新输入它们似乎很简单但很笨拙:-)

当我来到 Draw Items 时,它们包含代码 sn-p,不会因盒子而异(如上所示,但还有代码 sn-ps,其中逻辑不会改变但名称从 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。

【问题讨论】:

  • 那么就拥有一个并使用同一个......这不像你有不同的逻辑要担心。说实话,不太确定你的问题是什么
  • 另外...假设你保留了所有这些,你为什么要重新输入?你没听说过复制粘贴吗?
  • @Shreevadhan 的答案很可能是您正在寻找的。但要考虑的一件事 - 每次按钮点击的所有逻辑是否相同?
  • 逻辑是一样的,但命名发生了变化,我不知道如何实现。例如,当我来到 Draw 事件时,会有类似 if (e.Index >= 0) e.Graphics.DrawString(comboBox8.Items[e.Index].ToString(), e.Font, myBrush, e .Bounds, StringFormat.GenericDefault);将 8 替换为 9,依此类推。
  • 如果我理解正确,那么您可以使用sender 并将其转换为ComboBox 以在逻辑中获取其Items。你能否在你的问题中包含这个逻辑,所以它更清楚一点,好吗?事实证明,这对这个问题非常重要。

标签: c# events event-handling


【解决方案1】:
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);
. . .

【讨论】:

  • OP 说“以编程方式生成事件处理程序”...这是如何生成事件处理程序的?
  • @musefan 我根据描述回答了这个问题,因为我发现标题无关紧要。
  • 是的......但标题是唯一一半类似于问题的东西。我知道这可能是 OP 应该做的,但我只是觉得这是一个非问题,这意味着它不应该有答案
  • @Shreevardhan 见上面的评论。有些代码不会改变,您的答案非常适合这些。但是有些 sn-ps 的逻辑不会改变,但名称会改变,这是我想要生成的而不是“重新输入”
  • @Musefan 批评很容易,但没有帮助。
【解决方案2】:

你可以这样做:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多