C#附加事件的行为不符合预期

时间:2017-01-31 05:30:06

标签: c# wpf

我通过推荐的书Sams Teach Yourself WPF in 24 Hours学习WPF。我在"小时9"在哪里处理RoutedEvents。下面的代码是我从本书中输入的代码。据我了解,ButtonBase.Click是按钮正在调用的附加事件。这是我期待的。

<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;
    }

我将代码修改为以下内容,以便在MessageBox失去焦点时尝试显示TextBox。按下Button时,也会发生MessageBox。有人可以帮助澄清我不理解的地方吗?

<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.");
    }

1 个答案:

答案 0 :(得分:1)

  

按下按钮时也会出现MessageBox。有人可以帮助澄清我不理解的地方吗?

TextBoxBase.LostFocus实际上与LostFocus完全相同 - 它在UIElement类中定义,它是TextBoxBase和{{1}的公共基类,即TextBoxBase / TextBox类没有定义自己的Button事件。它继承了LostFocus类的LostFocus事件。

所以这里发生的事情是当你点击一个按钮时会引发UIElement事件,因为之前点击的按钮或之前关注的元素在点击按钮时确实会丢失。