我刚接触 WPF,当我学习 Material 时遇到了奇怪的问题。
我构建了一个按钮,包含带有文本 block 的层,我想识别用户点击按钮本身的位置,“第一”、“第二”或“第三”(我输出一条消息)。
除了当用户点击左键(仅使用中键或右键)时按钮不会引发事件外,一切正常。
所以我的问题是:为什么当我用鼠标左键按下按钮本身时我没有收到消息框(而我用其他鼠标按钮收到消息框)?
XAML:
<Button Margin="145,152,144,102" Padding="5,5,5,5" HorizontalAlignment="Center" VerticalAlignment="Center" MouseDown="Button_MouseDown" Height="57" Width="214">
<WrapPanel>
<WrapPanel HorizontalAlignment="Center" VerticalAlignment="Center"></WrapPanel>
<TextBlock Foreground="Black" FontSize="24" MouseDown="TextBlockFirst_MouseDown" >First </TextBlock>
<TextBlock Foreground="Red" FontSize="24" MouseDown="TextBlockSecond_MouseDown">Second </TextBlock>
<TextBlock Foreground="Blue" FontSize="24" MouseDown="TextBlockThird_MouseDown" >Third </TextBlock>
</WrapPanel>
</Button>
代码:
private void TextBlockFirst_MouseDown(object sender, MouseButtonEventArgs e)
{
MessageBox.Show("You click on first");
}
private void TextBlockSecond_MouseDown(object sender, MouseButtonEventArgs e)
{
MessageBox.Show("You click on second");
}
private void TextBlockThird_MouseDown(object sender, MouseButtonEventArgs e)
{
MessageBox.Show("You click on third");
}
private void Button_MouseDown(object sender, MouseButtonEventArgs e)
{
// This event not working good
// only middle & right mouse buttons are recognized
MessageBox.Show("You click on the button");
}
谢谢!
最佳答案
MouseDown
事件是一个冒泡事件
,它从发起者冒泡到根父级。但是 Click
事件吞噬了 MouseDown
事件并且不允许该事件冒泡到 Button。
您可以使用 PreviewMouseDown
事件,这是一个隧道事件
,它从根隧道到其发起者。所以button会先得到这个事件,然后是后续的textBlock。
<Button PreviewMouseDown="Button_MouseDown">
.......
</Button>
请引用下面的快照以获得清晰的图片:
更新
仅 Hook 按钮上的 PreviewMouseDown
事件,并从各个文本 block 中删除处理程序。检查 e.OrignialSource
以查看 TextBlock
是否是实际的原始源或按钮。
private void Button_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
if (!(e.OriginalSource is TextBlock))
{
MessageBox.Show("You click on the button");
}
else
{
switch ((e.OriginalSource as TextBlock).Text)
{
case "First":
MessageBox.Show("You click on first");
break;
case "Second":
MessageBox.Show("You click on second");
break;
case "Third":
MessageBox.Show("You click on third");
break;
}
}
}
XAML
<Button PreviewMouseDown="Button_PreviewMouseDown" Height="57" Width="214">
<WrapPanel>
<WrapPanel HorizontalAlignment="Center" VerticalAlignment="Center"/>
<TextBlock Foreground="Black" FontSize="24">First</TextBlock>
<TextBlock Foreground="Red" FontSize="24">Second</TextBlock>
<TextBlock Foreground="Blue" FontSize="24">Third</TextBlock>
</WrapPanel>
</Button>
关于c# - wpf:无法识别左键单击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23040840/