我试图绘制贝塞尔曲线并绑定其所有值:
<PathFigure StartPoint="20,20" IsClosed="False">
<BezierSegment Point1="70,130" Point2="220,20" Point3="180,160"/>
</PathFigure>
所以在所有情况下,一个&#39;点&#39;或定义了StartPoint我希望将它独立地绑定到类中的值。
有没有办法比手动绑定每个属性更有效地做到这一点?
答案 0 :(得分:-1)
对于这个具体问题,您可以执行以下操作:
基本上我们仍在使用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
属性,因此您可以设置其父DataContext
对象的Path
属性。如下所示:
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;
现在已经完成了。