使用附加属性代替多绑定
在WPF中,可以使用附加属性来代替多绑定。为Polygon元素创建新的附加属性,绑定这些属性来设置点的x和y坐标。在这种情况下,可以使用PointCollectionConverter将字符串转换为PointCollection对象,这样便可以将Point列表转换为适当的点集合。
代码示例:
public static class PolygonExtension
{
public static readonly DependencyProperty PointsStringProperty =
DependencyProperty.RegisterAttached("PointsString",
typeof(string),
typeof(PolygonExtension),
new FrameworkPropertyMetadata(null, OnPointsStringChanged));
public static string GetPointsString(DependencyObject obj)
{
return (string)obj.GetValue(PointsStringProperty);
}
public static void SetPointsString(DependencyObject obj, string value)
{
obj.SetValue(PointsStringProperty, value);
}
private static void OnPointsStringChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
string pointsString = e.NewValue as string;
if (!string.IsNullOrEmpty(pointsString))
{
PointCollection points = (PointCollection)new PointCollectionConverter().ConvertFromString(pointsString);
Polygon polygon = obj as Polygon;
if (polygon != null)
{
polygon.Points = points;
}
}
}
}
使用示例: