多个按钮共享一个不起作用的事件处理程

时间:2013-01-27 15:31:37

标签: c# events event-handling

我在让EventHandler为多个按钮工作时遇到了一些困难。他们将执行相同的工作,即链接到相同的表单(ModuleTemplate),并使用与该模块相关的适当内容填充它。

我只粘贴了有问题的代码。它编译得很好,第一个按钮(btnAudioNotetaker)工作正常,其他按钮什么都不做。

public void createAudioNotetaker()
{
    //this button click event works
    btnAudioNotetaker.Click += new EventHandler((sender, e) => btnModule_Click(sender, e, audioNotetakerDict, videoPathDict, pdfPathDict, audioPathDict));
}

public void createClaroRead()
{
    //this one doesn't work
    btnClaroRead.Click += new EventHandler((sender, e) => btnModule_Click(sender, e, audioNotetakerDict, videoPathDict, pdfPathDict, audioPathDict));
}

void btnModule_Click(object sender, EventArgs e, OrderedDictionary pageContent, OrderedDictionary videoPathDict, OrderedDictionary pdfPathDict, OrderedDictionary audioPathDict)
{
    //i want to use this event for each button
    ModuleTemplate newForm = new ModuleTemplate(pageContent, videoPathDict, pdfPathDict, audioPathDict);
    newForm.Show();
    this.Hide();
}

2 个答案:

答案 0 :(得分:0)

Lambdas很酷,但我觉得这段代码更清晰。它可能会或可能不会解决您的问题(尝试此代码时可能会遇到编译器错误),但维护起来会更容易。

public void createAudioNotetaker()
{
    //this button click event works
    btnAudioNotetaker.Click += commonClickHandler;
}

public void createClaroRead()
{
    //this one doesn't work
    btnClaroRead.Click += commonClickHandler;
}

void commonClickHandler(object sender, EventArgs e)
{
    btnModule_Click(sender, e, audioNotetakerDict, videoPathDict, pdfPathDict, audioPathDict));
} 

void btnModule_Click(object sender, EventArgs e, OrderedDictionary pageContent, OrderedDictionary videoPathDict, OrderedDictionary pdfPathDict, OrderedDictionary audioPathDict)
{
    //i want to use this event for each button
    ModuleTemplate newForm = new ModuleTemplate(pageContent, videoPathDict, pdfPathDict, audioPathDict);
    newForm.Show();
    this.Hide();
}

答案 1 :(得分:0)

我的错误,正如上面的评论所示,我没有在我的switch和case语句中调用我的createClaroRead函数。这种愚蠢的事情要忽视。

感谢大家的回复。