views:

310

answers:

2

Hi,

I was learning about routed events in wpf and I tries the following example,

File -- Window1.xaml

<ScrollViewer VerticalScrollBarVisibility="Auto">
    <UniformGrid MouseDown="UniformGrid_MouseDown">
        <Button x:Name="Button1">1</Button>
        <Button x:Name="Button2">2</Button>
        <Button x:Name="Button3">3</Button>
        <Button x:Name="Button4">4</Button>
        <Button x:Name="Button5">5</Button>
        <Button x:Name="Button6">6</Button>
        <Button x:Name="Button7">7</Button>
        <Button x:Name="Button8">8</Button>
        <Button x:Name="Button9">9</Button>
    </UniformGrid>
</ScrollViewer>

File -- Window1.xaml.cs

private void UniformGrid_MouseDown(object sender, MouseButtonEventArgs e)
{
    Button aTargetButton = e.Source as Button;
    if (aTargetButton != null)
    {
        aTargetButton.Background = Brushes.Azure;
        aTargetButton.LayoutTransform = new RotateTransform(45);
        if (myPreviouslyClickedButton != null)
        {
            myPreviouslyClickedButton.Background = Brushes.White;
            myPreviouslyClickedButton.LayoutTransform = new RotateTransform(0);
        }
        myPreviouslyClickedButton = aTargetButton;
    }
}

When I ran these snippets, the corresponding button undergoes a Angular Transformation only when I do a right click over it (even though I have subscribed for MouseDown). Can you help me out with this?

Update:

This snippet seems to work if i replace the button with an ellipse. Why can't the button react to left clicks when an ellipse can. Also the events are not raised if i click on the same ellipse more then once

A: 

This is working correctly. Internally, the Button handles the MouseDown event to know when to fire off its Click event. I've found that Snoop is a great tool for tracking down problems with WPF events, or to just get a better understanding of how they work.

Andy
+1  A: 

Your mouse down event is being handled by the button.

If you want your grid to handle the button events, then you might do something like:

 <ScrollViewer VerticalScrollBarVisibility="Auto">
    <UniformGrid Button.Click="UniformGrid_Click">
        <Button x:Name="Button1" Margin="10">1</Button>
        <Button x:Name="Button2">2</Button>
        <Button x:Name="Button3">3</Button>
        <Button x:Name="Button4">4</Button>
        <Button x:Name="Button5">5</Button>
        <Button x:Name="Button6">6</Button>
        <Button x:Name="Button7">7</Button>
        <Button x:Name="Button8">8</Button>
        <Button x:Name="Button9">9</Button>
    </UniformGrid>
    </ScrollViewer>

and change the source to something like:

private void UniformGrid_Click(object sender, RoutedEventArgs e)
    {
        // Your code here
    }

There's an msdn article here that would be worth a read.

corey broderick