【问题标题】:How do I pass an event handler as a method parameter?如何将事件处理程序作为方法参数传递?
【发布时间】:2011-01-11 16:25:45
【问题描述】:

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

下面的代码得到错误:

最好的重载方法匹配 '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);
            }
        }
    }
}

【问题讨论】:

    标签: c# parameters delegates methods


    【解决方案1】:

    您不能将鼠标按钮事件 args 处理程序转换为普通的 EventHandler - 请尝试在构造函数中使用 EventHandler&lt;MouseButtonEventArgs&gt;

    【讨论】:

      猜你喜欢
      • 2021-08-24
      • 2011-05-02
      • 1970-01-01
      • 1970-01-01
      • 2012-08-30
      • 2018-12-05
      • 1970-01-01
      相关资源
      最近更新 更多