【问题标题】:Add event handler (MouseDown) dynamically for PathFigure C# WPF为 PathFigure C# WPF 动态添加事件处理程序(MouseDown)
【发布时间】:2017-03-15 13:51:49
【问题描述】:

我用这段代码从点动态创建了一个对象:

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

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

poly.MouseDown += new MouseButtonEventHandler(poly_MouseDown);

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

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

解决方案是什么,或者有什么好的解决方法可以解决这个问题?也许以某种方式投射或转换它?

【问题讨论】:

标签: wpf canvas polyline pathgeometry figures


【解决方案1】:

在我看来,您正在跳过一个关键步骤。 先声明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);

【讨论】:

    猜你喜欢
    • 2010-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-15
    • 1970-01-01
    • 2014-07-06
    • 2020-03-06
    相关资源
    最近更新 更多