2014-09-13 55 views
1

我正在使用下面的代码来查看鼠标右键何时单击,是否碰到目标(Drawing)。如何检查目标是否在WPF中未命中

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

但我在哪里可以显示消息,指出目标是不是命中? 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; 
} 

回答

2

有一些一流水平标志,以指示命中是否成功与否。从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; 
} 
+0

感谢罗希特,这工作,但不是很奇怪,这是没有返回一个值? – Vahid 2014-09-13 15:06:02

+0

其他重载你通过Visual和Point传递给你的结果,但是当你提供回调比它不会返回结果是有意义的。 – 2014-09-13 15:12:44

+0

另一个超载接受矩形几何而不是Point? – Vahid 2014-09-13 15:18:08

2

除了什么罗希特说,你也可以使用本地标志和这样一个匿名回调方法:

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"); 
    } 
} 
+0

谢谢克莱门斯,我正在寻找这样的事实。这样我就可以拥有击中和不击中的逻辑。 – Vahid 2014-09-13 15:16:39

相关问题