【问题标题】:How to check if a target was not hit in WPF如何检查 WPF 中是否未命中目标
【发布时间】:2014-09-13 14:56:32
【问题描述】:

我正在使用下面的代码来查看鼠标右键单击的时间,它是否击中目标 (Drawing)。

现在,如果鼠标击中目标,将显示一条消息,说明我们击中了目标。

但是我可以在哪里显示目标命中的消息? VisualTreeHelper.HitTest() 似乎没有返回指示目标是否被击中的值。

private void OnMouseRightButtonUp(object sender, MouseButtonEventArgs e)
{
    var x = MousePos.RightDown.X;
    var y = MousePos.RightDown.Y;

    var hitRect = new Rect(x - 2, y - 2, 4, 4);
    var geom = new RectangleGeometry(hitRect);

    VisualTreeHelper.HitTest(Drawing, 
                             null, 
                             MyCallback, 
                             new GeometryHitTestParameters(geom));

    // Where should I put the MessageBox.Show("You did not hit the target");
    // If I put it here it is displayed anyway

}

private HitTestResultBehavior MyCallback(HitTestResult result)
{
    MessageBox.Show("You hit the target");
    return HitTestResultBehavior.Stop;
}

【问题讨论】:

    标签: c# wpf hittest


    【解决方案1】:

    有一些类级别的标志来指示命中是否成功。从 MyCallback 将标志设置为 true 并根据该标志显示消息。

    bool isTargetHit;    
    private void OnMouseRightButtonUp(object sender, MouseButtonEventArgs e)
    {
        isTargetHit = false;
    
        .......
        VisualTreeHelper.HitTest(Drawing, 
                                 null, 
                                 MyCallback, 
                                 new GeometryHitTestParameters(geom));
    
        if(isTargetHit)
        {
            MessageBox.Show("You hit the target");
        }
        else
        {
            MessageBox.Show("You did not hit the target");
        } 
    }
    
    private HitTestResultBehavior MyCallback(HitTestResult result)
    {
        isTargetHit = true;
        return HitTestResultBehavior.Stop;
    }
    

    【讨论】:

    • 感谢 Rohit,这可行,但它没有返回值不是很奇怪吗?
    • 传递 Visual 和 Point 的其他重载会得到结果,但是当您提供回调时,它不会返回有意义的结果。
    • 另一个重载也接受矩形几何而不是点?
    • @Vahid 不,只有一个带有 Point 参数。请参阅overload list
    • 感谢 Rohit 和 Clemens 的回答。
    【解决方案2】:

    除了 Rohit 所说的之外,您还可以像这样使用本地标志和匿名回调方法:

    private void OnMouseRightButtonUp(object sender, MouseButtonEventArgs e)
    {
        bool isTargetHit = false;
    
        VisualTreeHelper.HitTest(
            Drawing,
            null,
            r =>
            {
                isTargetHit = true;
                return HitTestResultBehavior.Stop;
            },
            new GeometryHitTestParameters(geom));
    
        if (isTargetHit)
        {
            MessageBox.Show("You hit the target");
        }
        else
        {
            MessageBox.Show("You did not hit the target");
        }
    }
    

    【讨论】:

    • 谢谢克莱门斯,我实际上正在寻找这样的东西。这样一来,我就有了在一个地方击中和不击中的逻辑。
    猜你喜欢
    • 1970-01-01
    • 2018-07-05
    • 2016-07-31
    • 1970-01-01
    • 2012-10-06
    • 1970-01-01
    • 2021-07-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多