If you're setting Path.Data directly, you won't be able to edit it in code behind. If you want to be able to do that, you should use PathGeometry
instead. From MSDN
As you can see from the preceding
examples, the two mini-languages are
very similar. It's always possible to
use a PathGeometry in any situation
where you could use a StreamGeometry;
so which one should you use? Use a
StreamGeometry when you don't need to
modify the path after creating it; use
a PathGeometry if you do need to
modify the path.
The following two Path's are equivalent, the later one can be modified in code behind
<!-- Path 1: Using StreamGeometry -->
<Path x:Name="MyPath"
Stroke="Black"
StrokeThickness="10"
Margin="20"
Data="M 10,10 L 100,10 L 100,200 L 10,200 Z"/>
<!-- Path 2: Using PathGeometry-->
<Path x:Name="MyPath2"
Stroke="Black"
StrokeThickness="10"
Margin="20">
<Path.Data>
<PathGeometry>
<PathGeometry.Figures>
<PathFigure x:Name="figure1" StartPoint="10, 10" IsClosed="True">
<LineSegment x:Name="line1" Point="100, 10"/>
<LineSegment x:Name="line2" Point="100, 200"/>
<LineSegment x:Name="line3" Point="10, 200"/>
</PathFigure>
</PathGeometry.Figures>
</PathGeometry>
</Path.Data>
</Path>
To modify MyPath2 in code behind, you can access the PathFigure
and LineSegment
s either by Name
private void MovePathHorizontally()
{
figure1.StartPoint = new Point(figure1.StartPoint.X + 10, figure1.StartPoint.Y);
line1.Point = new Point(line1.Point.X + 10, line1.Point.Y);
line2.Point = new Point(line2.Point.X + 10, line2.Point.Y);
line3.Point = new Point(line3.Point.X + 10, line3.Point.Y);
}
or like this
private void MovePathHorizontally()
{
PathGeometry pathGeometry = MyPath2.Data as PathGeometry;
PathFigureCollection pathFigures = pathGeometry.Figures;
foreach (PathFigure pathFigure in pathFigures)
{
pathFigure.StartPoint = new Point(pathFigure.StartPoint.X + 10, pathFigure.StartPoint.Y);
PathSegmentCollection pathSegments = pathFigure.Segments;
foreach (PathSegment pathSegment in pathSegments)
{
if (pathSegment is LineSegment)
{
LineSegment lineSegment = pathSegment as LineSegment;
lineSegment.Point = new Point(lineSegment.Point.X + 10, lineSegment.Point.Y);
}
}
}
}