代码之家  ›  专栏  ›  技术社区  ›  Edward Tanguay

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

  •  8
  • Edward Tanguay  · 技术社区  · 15 年前

    如何传递事件处理程序 文本块mousedown测试1 文本块mousedown测试2 以使它创建的文本块在单击时执行此事件处理程序?

    下面的代码获取错误:

    最佳重载方法匹配 '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);
                }
            }
        }
    }
    
    1 回复  |  直到 15 年前
        1
  •  7
  •   Andy    15 年前

    不能将鼠标按钮事件args处理程序强制转换为纯事件处理程序-请尝试 EventHandler<MouseButtonEventArgs> 而是在构造函数中。