简体   繁体   中英

How do I pass an event handler as a method parameter?

How can I pass the event handler TextBlock_MouseDown_Test1 or TextBlock_MouseDown_Test2 to SmartGrid so that the TextBlocks which it creates will execute this event handler when they are clicked?

The code below gets the error:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM