gpt4 book ai didi

c# - wpf:无法识别左键单击

转载 作者:太空狗 更新时间:2023-10-29 17:37:54 27 4
gpt4 key购买 nike

我刚接触 WPF,当我学习 Material 时遇到了奇怪的问题。

我构建了一个按钮,包含带有文本 block 的层,我想识别用户点击按钮本身的位置,“第一”、“第二”或“第三”(我输出一条消息)。

enter image description here

除了当用户点击左键(仅使用中键或右键)时按钮不会引发事件外,一切正常。

所以我的问题是:为什么当我用鼠标左键按下按钮本身时我没有收到消息框(而我用其他鼠标按钮收到消息框)?

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>

请引用下面的快照以获得清晰的图片:

enter image description here


更新

仅 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com