日期:2014-05-17  浏览次数:20908 次

WPF,请看下这个可视化层的命中测试

<Window x:Class="WPF1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Window1" Height="400" Width="700" MouseLeftButtonDown="Window_MouseLeftButtonDown">
    <Canvas Height="172" Name="canvas1" Width="210">
        <Ellipse Margin="20" Width="100" Name="ellipse1" Height="100" Stroke="Red" />
        <TextBlock Name="textblock1" Text="张三"/>
    </Canvas>
</Window>


private void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    Point pt = e.GetPosition((UIElement)sender); //获得鼠标坐标
    HitTestResult result = VisualTreeHelper.HitTest(ellipse1, pt); //获取鼠标点击到的可视对象
    if (result == null)
        return;
    MessageBox.Show("fgdfr6g");
    if (result.VisualHit as FrameworkElement != null)
    MessageBox.Show((result.VisualHit as FrameworkElement).Name);
}



上面的代码中,测试可视化层中的命中测试,我点击Textblock,为什么没有响应呢?难道没有点中Textblock吗?

------解决方案--------------------
HitTestResult result = VisualTreeHelper.HitTest((UIElement)sender, pt); //获取鼠标点击到的可视对象
改成这样才行,你是根据sender得到的pt

------解决方案--------------------
引用:
Quote: 引用:

HitTestResult result = VisualTreeHelper.HitTest((UIElement)sender, pt); //获取鼠标点击到的可视对象
改成这样才行,你是根据sender得到的pt

MSDN这个例子,也是和我写的差不多啊,也没有用Sender啊

你这里如果使用canvas1是不行的,因为你设置了Height和Width,却没有设置对其。
如果你的canvas的HorizontalAlignment=Left 并且 VerticalAlignment设置为Top,才可以,因为在MSDN中canvas的布局在window中是全布局的,也就是说Canvas的坐标系统和Window的是完全符合的,Window的坐标是从左上角为(0,0)点的,所以你的Canvas加上左上对齐,就能符合Window的坐标系统了。
------解决方案--------------------
Point pt = e.GetPosition((UIElement)sender); //获得鼠标坐标
HitTestResult result = VisualTreeHelper.HitTest(ellipse1, pt); //获取鼠标点击到的可视对象

HitTest中的第一个参数不是你要命中的东西,而是你的点的所依赖的Visual视图。
Point pt = e.GetPosition((UIElement)el