Search code examples
wpfbuttongridrouted-events

Same click event for both Button and Grid


I read about Routed events today and tried to provide same click event handler for both a normal button and a custom grid button. Stackpanel is handling the routed button click event, and to invoke same handler I am firing a click event from grid's mousedown event. Code is without error but not working as expected. Button click brings the messagebox but clicking the grid with mouse does nothing.

<Window x:Class="RoutedEventPr.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="550" Width="525">

<StackPanel  Background="Transparent" Button.Click="Button_Click_1">

    <Grid Width="200" Height="100" Background="Aqua" MouseDown="Grid_MouseDown_1">
        <Ellipse StrokeThickness="4" Width="200" Height="100" Fill="Beige"/>           
        <TextBlock Text="Press" HorizontalAlignment="Center" VerticalAlignment="Center"/>
    </Grid>

    <Button x:Name="SureBtn" Content="Pause !" Width="200" Margin="0 10 0 0"/>

    <Image HorizontalAlignment="Center" VerticalAlignment="Center" Width="200" Height="200" Source="I://fancybtn.jpg"/>

    <Label Content="Start the game"/>

</StackPanel>

    private void Grid_MouseDown_1(object sender, MouseButtonEventArgs e)
    {
        RaiseEvent(new RoutedEventArgs(Button.ClickEvent, this));
    }

    private void Button_Click_1(object sender, RoutedEventArgs e)
    {
        MessageBox.Show("Are you sure !");
    }

Solution

  • Button.Click event is routed event with bubbling strategy set to Bubble.

    That means it will bubble up to visual parent till root until it was handled. In your case, you raise an event from Window, so it will bubble up from Window to its parent which is null.

    You have to raise the event from child control of StackPanel so that it can bubble up to StackPanel.

    XAML

    <Grid x:Name="grid" Width="200" Height="100" Background="Aqua" 
          MouseDown="Grid_MouseDown_1">
        <Ellipse StrokeThickness="4" Width="200" Height="100" Fill="Beige"/>
        <TextBlock Text="Press" HorizontalAlignment="Center"
                   VerticalAlignment="Center"/>
    </Grid>
    

    Code behind

    private void Grid_MouseDown_1(object sender, MouseButtonEventArgs e)
    {
        grid.RaiseEvent(new RoutedEventArgs(Button.ClickEvent, this));
    }