wpf为动态按钮设置鼠标处理程序

时间:2017-02-10 19:45:35

标签: c# wpf

我正在尝试学习c#和wpf。我有一段代码可以正常显示控件。我还尝试创建一个鼠标按钮处理程序,当我调试它时,从不调用处理程序。这些按钮嵌套在几个StackPanel中,这似乎不是问题吗?

        StackPanel tabPanel = new StackPanel();
        for (int i = 0; i < 20; i++)
        {
            StackPanel micPanel = new StackPanel();
            micPanel.Orientation = Orientation.Horizontal;

            //  Add the Calibration Button
            Button micButton = new Button();
            micButton.Height = 25;
            micButton.Name = string.Format("Mic{0}", i);
            micButton.Content = string.Format("Mic{0}", ((20 * index) + i));
            micButton.MouseLeftButtonUp += new MouseButtonEventHandler(mic_MouseLeftButtonUp);
            micPanel.Children.Add(micButton);

            // Add the calibrated Value
            Label micLabel = new Label();
            micLabel.Height = 25;
            micLabel.Content = string.Format("Value: {0}", ((20 * index) + i));
            micPanel.Children.Add(micLabel);

            tabPanel.Children.Add(micPanel);
        }
        tab.Content = tabPanel;

处理程序如下所示:

    private void mic_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
    {
        Button but = sender as Button;
    }

我设置了一个断点,它从不调用处理程序?

2 个答案:

答案 0 :(得分:0)

这是典型的:使用preview事件处理程序确保它首先在树视图中引发。

micButton.PreviewMouseLeftButtonUp += new MouseButtonEventHandler(mic_MouseLeftButtonUp);

答案 1 :(得分:0)

为什么不处理Button的Click事件?

micButton.Click += new ClickEventHandler(mic_Click);
...

private void mic_Click(object sender, RoutedEventArgs e)
{
    Button but = sender as Button;
}

某些控件会“吞下”某些事件,但Button控件不会引发任何MouseButtonUp事件。它引发了Click事件。 Click事件实际上是LeftButtonDownLeftButtonUp事件的组合:

WPF MouseLeftButtonUp Not Firing

您可以在MSDN上的文档中阅读有关路由事件及其工作方式的更多信息:https://msdn.microsoft.com/en-us/library/ms742806%28v=vs.110%29.aspx