IvenBach
IvenBach

Reputation: 583

C# attached event not behaving as expected

I'm learning WPF through a recommended book Sams Teach Yourself WPF in 24 Hours. I'm in "Hour 9" where it's dealing with RoutedEvents. The code below is what I've typed from the book. As I understand it the ButtonBase.Click is the attached event that the buttons are calling. This works as I am expecting.

<StackPanel ButtonBase.Click="StackPanel_Click">
    <Button Content="Red" Foreground="Red"/>
    <Button Content="Green" Foreground="Green"/>
    <Button Content="Blue" Foreground="Blue"/>
    <TextBlock x:Name="Output"
               HorizontalAlignment="Center"
               Text="What color will you choose?"/>
</StackPanel>

    private void StackPanel_Click(object sender, RoutedEventArgs e)
    {

        Button button = (Button)e.Source;
        Output.Text=string.Format(
            $"You choose the color {button.Content}"
            );
        Output.Background = button.Foreground;
    }

I modify the code to what's seen below in an attempt to have the MessageBox display when the TextBox looses focus. The MessageBox also occurs when the Buttons are pushed. Can someone help clarify where I'm not understanding?

<StackPanel ButtonBase.Click="StackPanel_Click"
            TextBoxBase.LostFocus="StackPanel_LostFocus">
    <Button Content="Red" Foreground="Red"/>
    <Button Content="Green" Foreground="Green"/>
    <Button Content="Blue" Foreground="Blue"/>
    <TextBox HorizontalAlignment="Center">Here's some text.</TextBox>
    <TextBlock x:Name="Output"
               HorizontalAlignment="Center"
               Text="What color will you choose?"/>
</StackPanel>

    private void StackPanel_Click(object sender, RoutedEventArgs e)
    {

        Button button = (Button)e.Source;
        Output.Text=string.Format(
            $"You choose the color {button.Content}"
            );
        Output.Background = button.Foreground;
    }

    private void StackPanel_LostFocus(object sender, RoutedEventArgs e)
    {
        MessageBox.Show("The text box has lost focus.");
    }

Upvotes: 3

Views: 127

Answers (1)

mm8
mm8

Reputation: 169200

The MessageBox also occurs when the Buttons are pushed. Can someone help clarify where I'm not understanding?

TextBoxBase.LostFocus is actually the very same event as LostFocus - it is defined in the UIElement class which is a common base class of both TextBoxBase and Button, i.e. the TextBoxBase/TextBox class doesn't define its own LostFocus event. It inherits the LostFocus event from the UIElement class.

So what happens here is that the LostFocus event is raised when you click on a button as the previously clicked button, or the previously focused element, indeed loses when the button is clicked.

Upvotes: 1

Related Questions