我目前正在尝试从简单网格上的图像中捕获mousedown。我对事件发射没有任何问题,只是它发射了两次。因为点击两次最终会有不同的状态(它会显示一个展开的图像),直接进行第二次点击会导致问题。
我目前的代码如下:
XAML
<Window x:Class="WpfApplication.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid Background="Transparent" x:Name="MainContent" MouseDown="Generic_MouseDown">
<Image Source="http://www.blogcdn.com/www.engadget.com/media/2011/05/welcome-kansas-city-google-high-speed-internet.jpg" Height="100" Width="100" MouseDown="Generic_MouseDown"/>
</Grid>
</Window>
代码:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Generic_MouseDown(object sender, MouseButtonEventArgs e)
{
if (((FrameworkElement)e.Source).GetType() == typeof(System.Windows.Controls.Image))
{
Console.Out.WriteLine("image clicked");
}
else
{
Console.Out.WriteLine("grid clicked");
}
}
}
因此,当我点击图像时,它会两次发射mousedown。
谢谢!
答案 0 :(得分:13)
private void Generic_MouseDown(object sender, MouseButtonEventArgs e)
{
if (((FrameworkElement)e.Source).GetType()
== typeof(System.Windows.Controls.Image))
{
Debug.WriteLine("image clicked");
e.Handled = true;
}
else
{
Debug.WriteLine("grid clicked");
}
}
您需要将Handled属性设置为true。
答案 1 :(得分:6)
您需要将e.Handled设置为true,以防止事件从图像冒泡到网格。
实际上,正在发生的事情是在Image上引发事件,然后如果没有处理它会在Grid上引发,依此类推在可视树上。
答案 2 :(得分:1)
这是你的XAML&amp;你将[MouseDown =“Generic_MouseDown”] 两次添加到Grid&amp;图像
<Window x:Class="WpfApplication.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid Background="Transparent" x:Name="MainContent" MouseDown="Generic_MouseDown">
<Image Source="http://www.blogcdn.com/www.engadget.com/media/2011/05/welcome-kansas-city-google-high-speed-internet.jpg" Height="100" Width="100" MouseDown="Generic_MouseDown"/>
</Grid>
</Window>
在网格
中将其设为 ONE [MouseDown =“Generic_MouseDown”]<Window x:Class="WpfApplication.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid Background="Transparent" x:Name="MainContent" MouseDown="Generic_MouseDown">
<Image Source="http://www.blogcdn.com/www.engadget.com/media/2011/05/welcome-kansas-city-google-high-speed-internet.jpg" Height="100" Width="100" />
</Grid>
</Window>
或强>
在图片
中将其设为 ONE [MouseDown =“Generic_MouseDown”]<Window x:Class="WpfApplication.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid Background="Transparent" x:Name="MainContent">
<Image Source="http://www.blogcdn.com/www.engadget.com/media/2011/05/welcome-kansas-city-google-high-speed-internet.jpg" Height="100" Width="100" MouseDown="Generic_MouseDown"/>
</Grid>
</Window>