简体   繁体   中英

Add event handler (MouseDown) dynamically for PathFigure C# WPF

I created an object from points with this code, dynamically:

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 });

Now I want to add event handler for this object. Would not be a problem if object is a path or polyline type. I would just add event handler like this:

poly.MouseDown += new MouseButtonEventHandler(poly_MouseDown);

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

Problem is that I have to use Figures and PathGeometry which does not accept MouseDown event handlers. Since they are from System.Windows. Media class and Path/Polyline is from System.Windows. Shapes I can't find a solution to assign right event handler (MouseDown) to my Figure object.

What is the solution or is there any nice workaround solution for this problem? Maybe cast or convert it somehow?

As I see it you're skipping a crucial step. Declare the Path Object first, give it the event, and then insert it into your 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM