对于这个特定的问题,你可以做如下:
基本上,我们仍然使用MVVM模式。首先你需要PathPoint
类和PathFigureViewModel
类代表你的数据。
public class PathPoint
{
public int X
{
get;
set;
}
public int Y
{
get;
set;
}
}
和
public class PathFigureViewModel
{
public PathPoint StartPoint
{
get; set;
}
public PathPoint Point1
{
get; set;
}
public PathPoint Point2
{
get; set;
}
public PathPoint Point3
{
get; set;
}
}
然后,你可以定义你PathFigure
如下:
<PathFigure x:Name="PathFigure1" StartPoint="{Binding StartPoint, Converter={StaticResource PointConvertor}}" IsClosed="False">
<BezierSegment Point1="{Binding Point1, Converter={StaticResource PointConvertor}}" Point2="{Binding Point2, Converter={StaticResource PointConvertor}}" Point3="{Binding Point3, Converter={StaticResource PointConvertor}}"/>
</PathFigure>
注意,上面有它转换PathPoint
到System.Windows.Point
如下转换器:
public class PointToPathPointConvertor : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var p = value as PathPoint;
return new System.Windows.Point(p.X, p.Y);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return null;
}
}
最后你需要设置DataContext。由于PathFigure
未公开DataContext
属性,因此可以设置其父Path
对象的DataContext
属性。类似如下:
PathFigureViewModel vm = new PathFigureViewModel();
vm.StartPoint = new PathPoint() { X = 20, Y = 20 };
vm.Point1 = new PathPoint() { X = 70, Y = 130 };
vm.Point2 = new PathPoint() { X = 220, Y = 20 };
vm.Point3 = new PathPoint() { X = 180, Y = 160 };
this.Path.DataContext = vm;
现在完成了。