![](/img/trans.png)
[英]How can I correctly pass an input parameter to an event handler method in C#?
[英]How do I pass an event handler as a method parameter?
如何将事件处理程序TextBlock_MouseDown_Test1或TextBlock_MouseDown_Test2传递给SmartGrid,以便它创建的TextBlocks在单击时将执行此事件处理程序?
下面的代码得到错误:
'TestDel234.SmartGrid.SmartGrid(TestDel234.Window1,System.Collections.Generic.List,System.EventHandler)'的最佳重载方法匹配有一些无效的参数
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
namespace TestDel234
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
List<string> items = new List<string> { "one", "two", "three" };
SmartGrid sg = new SmartGrid(this, items, TextBlock_MouseDown_Test1);
}
private void TextBlock_MouseDown_Test1(object sender, MouseButtonEventArgs e)
{
MessageBox.Show("testing1");
}
private void TextBlock_MouseDown_Test2(object sender, MouseButtonEventArgs e)
{
MessageBox.Show("testing2");
}
}
public class SmartGrid
{
public SmartGrid(Window1 window, List<string> items, EventHandler eventHandler)
{
foreach (var item in items)
{
TextBlock tb = new TextBlock();
tb.Text = item;
tb.MouseDown += new MouseButtonEventHandler(eventHandler);
window.MainContent.Children.Add(tb);
}
}
}
}
您不能将鼠标按钮事件args处理程序转换为普通的EventHandler - 而是尝试在构造函数中使用EventHandler<MouseButtonEventArgs>
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.