-2

Here's the C# code:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }
    private void Button_Click(object sender, RoutedEventArgs e)
    {
        
        txt1.Text = "Button is Clicked";
    }

    private void StackPanel_Click(object sender, RoutedEventArgs e)
    {
        txt2.Text = "Click event is bubbled to Stack Panel";
    }

    private void Window_Click(object sender, RoutedEventArgs e)
    {
        txt3.Text = "Click event is bubbled to Window";
    }
}

And here's the WPF code:

 <Grid>
    <StackPanel Margin = "20" ButtonBase.Click = "StackPanel_Click">

        <StackPanel Margin = "10">
            <TextBlock Name = "txt1" FontSize = "18" Margin = "5" Text = "This is a TextBlock 1" />
            <TextBlock Name = "txt2" FontSize = "18" Margin = "5" Text = "This is a TextBlock 2" />
            <TextBlock Name = "txt3" FontSize = "18" Margin = "5" Text = "This is a TextBlock 3" />
        </StackPanel>

        <Button Margin = "10" Content = "Click me" Click = "Button_Click" Width = "80"/>
    </StackPanel>
</Grid>

When I click the button, the app reports the Button and Stack Panel click event but not the Window. Why?

Ron
  • 2,435
  • 3
  • 25
  • 34

1 Answers1

0

Why?

Because you haven't attached any handler for the window. You could do this programmatically in the constructor:

public MainWindow()
{
    InitializeComponent();
    AddHandler(System.Windows.Controls.Primitives.ButtonBase.ClickEvent, 
        new RoutedEventHandler(Window_Click));
}

...or in the XAML markup:

<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        Title="Window32" Height="450" Width="800
        ButtonBase.Click="Window_Click">
mm8
  • 163,881
  • 10
  • 57
  • 88