为PathFigure C#WPF动态添加事件处理程序(MouseDown)

时间:2016-11-02 09:46:02

标签: wpf canvas polyline pathgeometry figures

我使用此代码从点创建了一个对象,动态地:

SolidColorBrush brushColor = (SolidColorBrush)new BrushConverter().ConvertFromString(_brushColor);

PathFigure figures = new PathFigure();
figures.StartPoint = points[0];
points.RemoveAt(0);
figures.Segments = new PathSegmentCollection(points.Select((p, i) => new LineSegment(p, i % 2 == 0)));
PathGeometry pg = new PathGeometry();
pg.Figures.Add(figures);
canvas.Children.Add(new Path { Stroke = brushColor, StrokeThickness = 3, Data = pg });

现在我想为这个对象添加事件处理程序。如果object是路径或折线类型,则不会有问题。我只想添加这样的事件处理程序:

poly.MouseDown += new MouseButtonEventHandler(poly_MouseDown);

void poly_MouseDown(object sender, MouseButtonEventArgs e)
{
     //code
}

问题是我必须使用不接受MouseDown事件处理程序的Figures和PathGeometry。因为它们来自System.Windows。媒体类和Path / Polyline来自System.Windows。形状我找不到分配正确事件处理程序的解决方案( MouseDown)到我的Figure对象。

解决方案是什么或者是否有针对此问题的解决方案?也许以某种方式投射或转换它?

1 个答案:

答案 0 :(得分:0)

在我看来,你正在跳过关键的一步。 首先声明Path对象,为其指定事件,然后将其插入Canvas

SolidColorBrush brushColor = (SolidColorBrush)new BrushConverter ().ConvertFromString (_brushColor);

PathFigure figures = new PathFigure ();
figures.StartPoint = points[0];
points.RemoveAt (0);
figures.Segments = new PathSegmentCollection (points.Select ((p, i) => new LineSegment (p, i % 2 == 0)));
PathGeometry pg = new PathGeometry ();
pg.Figures.Add (figures);
Path pgObject = new Path({ Stroke = brushColor, StrokeThickness = 3, Data = pg });
pgObject.MouseDown+=new MouseButtonEventHandler(poly_MouseDown);
canvas.Children.Add (pgObject);
相关问题