如何在WPF中检查目标是否未命中
本文关键字:是否 目标 检查 WPF | 更新日期: 2023-09-27 18:21:55
我使用下面的代码来查看鼠标右键何时被单击,是否击中目标(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;
}
有一些类级别的标志来指示命中是否成功。将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所说的,您还可以使用本地标志和匿名回调方法,如下所示:
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");
}
}