1

I am attempting to learn c# and wpf. I have a segment of code that works in that it shows the controls correctly. I also attempt to create a mouse button handler and when I debug it, the handler is never called. The buttons are nested within a couple of StackPanels, that can't seem to be the problem?

        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;

The handler looks like this:

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

I set a breakpoint and it never calls the handler?

Sting
  • 363
  • 6
  • 18

2 Answers2

0

This is typical: use the preview event handler to make sure it is raised first in the tree view.

micButton.PreviewMouseLeftButtonUp += new MouseButtonEventHandler(mic_MouseLeftButtonUp);
Community
  • 1
  • 1
  • Is this because some other device is consuming the click and it never gets to my handler? Is this something I should always use? Or is it just because of the container it is in? – Sting Feb 10 '17 at 20:18
  • 1
    @Sting There is online documentation available, that explains this in detail. – Clemens Feb 10 '17 at 20:28
0

Why don't you handle the Click event of the Button?

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

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

Certain controls do "swallow" certain events but the Button control doesn't raise any MouseButtonUp event. It raises a Click event. The Click event is actually a combination of the LeftButtonDown and LeftButtonUp event:

WPF MouseLeftButtonUp Not Firing

You can read more about routed events and how they work in the documentation on MSDN: https://msdn.microsoft.com/en-us/library/ms742806%28v=vs.110%29.aspx

Community
  • 1
  • 1
mm8
  • 163,881
  • 10
  • 57
  • 88