更新时间:2023-11-18 16:07:10
您可以将鼠标按下事件处理程序添加到 Canvas,而不是 Shape 对象,然后执行 视觉层中的命中测试(虽然API有点奇怪)带有命中测试几何体,例如椭圆.Canvas 需要将其 Background
设置为(例如,设置为 Transparent
)以接收鼠标事件.
You could add a mouse down event handler to the Canvas, instead of the Shape objects, and then do Hit Testing in the Visual Layer (although the API is a bit strange) with a hit test geometry, for example an ellipse. The Canvas needs to have its Background
set (e.g. to Transparent
) to receive mouse events.
抱歉,这是 C#,但我不会说 VB:
Sorry that this is C#, but i don't speak VB:
private void Canvas_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
Canvas canvas = sender as Canvas;
EllipseGeometry hitTestGeometry =
new EllipseGeometry(e.GetPosition(canvas), 10d, 10d);
Shape hitShape = null;
HitTestResultCallback hitTestCallback =
result =>
{
hitShape = result.VisualHit as Shape;
return hitShape != null ? HitTestResultBehavior.Stop : HitTestResultBehavior.Continue;
};
VisualTreeHelper.HitTest(canvas, null, hitTestCallback, new GeometryHitTestParameters(hitTestGeometry));
if (hitShape != null)
{
System.Diagnostics.Trace.TraceInformation("hit shape: {0}", hitShape);
}
}
这是等效的 VB 代码.VB 不支持多行 lambda 表达式,因此必须显式声明命中测试回调
Here is the equivalent VB code. VB does not support multiline lambda expressions so the hit test callback has to be declared explicitly
Private Function htCallback(ByVal result As HitTestResult) _
As HitTestResultBehavior
Dim hitShape As Shape = Nothing
hitShape = TryCast(result.VisualHit, Shape)
If hitShape IsNot Nothing Then
'do something
End If
Return If(hitShape IsNot Nothing, HitTestResultBehavior.[Stop], _
HitTestResultBehavior.[Continue])
End Function
Private Sub Canvas_MouseLeftButtonDown(ByVal sender As Object, _
ByVal e As MouseButtonEventArgs) Handles Canvas1.MouseRightButtonDown
Dim canvas As Canvas = TryCast(sender, Canvas)
Dim hitTestGeometry As New EllipseGeometry(e.GetPosition(canvas), 10.0, 10.0)
Dim hitTestCallback As HitTestResultCallback = _
New HitTestResultCallback(AddressOf htCallback)
VisualTreeHelper.HitTest(canvas, Nothing, hitTestCallback, _
New GeometryHitTestParameters(hitTestGeometry))
End Sub