我正在尝试使用MouseButtonEventHandler在画布中添加一个drawingvisual对象。但无法获得点击事件。我在这里做错了什么?
public class VisualHost : UIElement
{
public Visual myVisual { get; set; }
public VisualHost()
{
Visibility = Visibility.Visible;
IsHitTestVisible = true;
MouseLeftButtonUp += new MouseButtonEventHandler(MyVisualHost_MouseLeftButtonUp);
}
protected override int VisualChildrenCount
{
get { return myVisual != null ? 1 : 0; }
}
protected override Visual GetVisualChild(int index)
{
return myVisual;
}
//mouse event
private void MyVisualHost_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
MessageBox.Show("You clicked a drawing-Visual");
}
}
private void AddMyVisualObject()
{
GeometryDrawing myRectDrawing = new GeometryDrawing(Brushes.Yellow, new Pen(Brushes.White, 1.5), new RectangleGeometry(new Rect(0, 0, 200, 100)));
DrawingVisual myDV = new DrawingVisual();
DrawingContext myDC = myDV.RenderOpen();
myDC.DrawDrawing(myRectDrawing);
myDC.Close();
VisualHost myVH = new VisualHost { myVisual = myDV };
myDrawingCanvas.Children.Add(myVH);
}
请帮助,在单击DrawingVisual时如何触发事件?
最佳答案
您必须使用VisualCollection
来承载您的Visual
元素,并自己对它们进行命中测试:
public class VisualHost : FrameworkElement
{
private VisualCollection Children { get; set; }
public VisualHost()
{
this.Children = new VisualCollection(this);
this.MouseLeftButtonUp += MyVisualHost_MouseLeftButtonUp;
}
public void AddChild(Visual visual)
{
this.Children.Add(visual);
}
protected override int VisualChildrenCount => this.Children.Count;
protected override Visual GetVisualChild(int index) => this.Children[index];
//mouse event
private void MyVisualHost_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
// Initiate the hit test by setting up a hit test result callback method.
VisualTreeHelper.HitTest(this, null, OnVisualClicked, new PointHitTestParameters(e.GetPosition((UIElement) sender)));
}
private HitTestResultBehavior OnVisualClicked(HitTestResult result)
{
if (result.VisualHit.GetType() == typeof(DrawingVisual))
{
MessageBox.Show("You clicked a DrawingVisual");
}
// Stop the hit test enumeration of objects in the visual tree.
return HitTestResultBehavior.Stop;
}
}
然后初始化主机:
private void AddMyVisualObject()
{
GeometryDrawing myRectDrawing = new GeometryDrawing(Brushes.Yellow, new Pen(Brushes.White, 1.5), new RectangleGeometry(new Rect(0, 0, 200, 100)));
DrawingVisual myDV = new DrawingVisual();
DrawingContext myDC = myDV.RenderOpen();
myDC.DrawDrawing(myRectDrawing);
myDC.Close();
VisualHost myVH = new VisualHost();
myVH.AddChild(myDV);
this.Canvas.Children.Add(myVH);
}
有关更多信息,请参见MSDN。
关于c# - 在自定义DrawingVisual Object UIElement上获取mouseclick事件时遇到麻烦,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55240072/