我通过推荐的书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.");
}
答案 0 :(得分:1)
按下按钮时也会出现MessageBox。有人可以帮助澄清我不理解的地方吗?
TextBoxBase.LostFocus
实际上与LostFocus
完全相同 - 它在UIElement
类中定义,它是TextBoxBase
和{{1}的公共基类,即TextBoxBase / TextBox类没有定义自己的Button
事件。它继承了LostFocus
类的LostFocus
事件。
所以这里发生的事情是当你点击一个按钮时会引发UIElement
事件,因为之前点击的按钮或之前关注的元素在点击按钮时确实会丢失。