如何将鼠标单击方法作为参数传递?

时间:2010-03-10 12:45:15

标签: c# parameters delegates action func

我想制作一个扩展程序方法,它使用按钮填充堆叠面板。

为了做到这一点,我必须传入鼠标点击处理程序

mouseClickHandler参数必须在哪种类型?

我知道这些都是这样的,但它们都不起作用:

  • delegate
  • Func<object, RoutedEventArgs>
  • Action<>

代码:

public static void FillMenuWithPages(this StackPanel spMenu, string menuIdCode, 
            PagingManager pagingManager, ??????? mouseClickHandler)
{
    var menuPageItems = PageItems.GetPageItemsWithMenu(menuIdCode);
    spMenu.Children.Clear();
    foreach (var pageItem in menuPageItems)
    {
        var button = new Button();
        button.Content = pageItem.Title;
        button.Margin = new Thickness { Right = 3 };
        button.Tag = pageItem.IdCode;
        button.Cursor = Cursors.Hand;
        button.Click += new RoutedEventHandler(mouseClickHandler);
        if (pageItem.IdCode == pagingManager.CurrentPageItemIdCode)
            button.IsEnabled = false;
        spMenu.Children.Add(button);
    }
}

我会这样称呼:

QuickMenu.FillMenuWithPages("quick", PagingManager, Menu_Button_Click);

这是鼠标点击操作:

void Menu_Button_Click(object sender, RoutedEventArgs e)
{
    string pageItemIdCode = ((FrameworkElement)sender).Tag.ToString();
    PagingManager.SwitchPage(pageItemIdCode);
}

2 个答案:

答案 0 :(得分:1)

将其传递为RoutedEventHandler,如此:

public static void FillMenuWithPages(this StackPanel spMenu, string menuIdCode,
            PagingManager pagingManager, RoutedEventHandler mouseClickHandler)

答案 1 :(得分:1)

这取决于它是WPF还是Winforms应用程序。对于WPF,它将是RoutedEventHandler(如ButtonBase.Click文档中所述)。对于winforms,它是EventHandler(如Control.Click文档中所示)。