Asf*_*sfK 9 c# wpf events mouseevent
我最近在WPF,当我学习我遇到的奇怪问题的材料.
我构建了一个按钮,包含带有文本块的图层,我想要识别用户点击"按钮本身,'第一','第二或'第三'的位置(我输出一条消息).

一切正常,但当用户点击左键(只有中间或右键)时,按钮不会引发事件.
所以我的问题:为什么当我用鼠标左键按下按钮时我没有收到消息框(我收到带有其他鼠标按钮的消息框)?
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>
Run Code Online (Sandbox Code Playgroud)
码:
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");
}
Run Code Online (Sandbox Code Playgroud)
谢谢!
Roh*_*ats 15
MouseDown事件是bubbling event从其发起者到其根父母的气泡.但Click事件会影响MouseDown事件,并且不允许事件冒泡到Button.
您可以使用PreviewMouseDown事件,这是一个tunnelling event从根隧道,它的鼻祖.因此按钮将首先获得此事件,然后是后续的textBlock.
<Button PreviewMouseDown="Button_MouseDown">
.......
</Button>
Run Code Online (Sandbox Code Playgroud)
有关清晰的图片,请参阅下面的快照:

UPDATE
仅挂钩PreviewMouseDown按钮上的事件并从单个textBlocks中删除处理程序.检查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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)