gpt4 book ai didi

c# - 如何将事件处理程序作为方法参数传递?

转载 作者:太空狗 更新时间:2023-10-29 19:38:12 25 4
gpt4 key购买 nike

如何将事件处理程序 TextBlock_MouseDown_Test1TextBlock_MouseDown_Test2 传递给 SmartGrid,以便它创建的 TextBlocks 在被单击时执行此事件处理程序?

下面的代码得到错误:

The best overloaded method match for 'TestDel234.SmartGrid.SmartGrid(TestDel234.Window1, System.Collections.Generic.List, System.EventHandler)' has some invalid arguments

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

最佳答案

您不能将鼠标按钮事件参数处理程序转换为普通的 EventHandler - 尝试 EventHandler<MouseButtonEventArgs>而不是在构造函数中。

关于c# - 如何将事件处理程序作为方法参数传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2176223/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com