第一种方法中的绑定仅在SegmentPoint
属性更改时更新,即分配给新集合。因此它不需要是 ObservableCollection。只需创建一个新集合并引发PropertyChanged事件。
public class ViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private ICollection<Point> segmentPoints;
public ICollection<Point> SegmentPoints
{
get { return segmentPoints; }
set
{
segmentPoints = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("SegmentPoints"));
}
}
}
}
但是,在您的第二种方法中,技巧不是绑定 PathGeometry 的Figure
属性,而是直接在 XAML 或代码中分配 PathFigureCollection。
<Canvas Background="Transparent" MouseMove="Canvas_MouseMove">
<Path Stroke="Blue" StrokeThickness="3">
<Path.Data>
<PathGeometry>
<PathGeometry.Figures>
<PathFigureCollection x:Name="figures"/>
</PathGeometry.Figures>
</PathGeometry>
</Path.Data>
</Path>
</Canvas>
在代码中添加段并修改它们的属性:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
var segment = new BezierSegment(new Point(100, 0), new Point(200, 300), new Point(300, 100), true);
var figure = new PathFigure();
figure.Segments.Add(segment);
figures.Add(figure);
}
private void Canvas_MouseMove(object sender, MouseEventArgs e)
{
var firstSegment = figures[0].Segments[0] as BezierSegment;
firstSegment.Point2 = e.GetPosition(sender as IInputElement);
}
}
您也可以Figures
在代码中创建属性,如下所示。MainWindow 类定义了一个Figures
属性,该属性分配给Figures
PathGeometry 的属性。
<Canvas Background="Transparent" MouseMove="Canvas_MouseMove">
<Path Stroke="Blue" StrokeThickness="3">
<Path.Data>
<PathGeometry x:Name="geometry"/>
</Path.Data>
</Path>
</Canvas>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
var segment = new BezierSegment(new Point(100, 0), new Point(200, 300), new Point(300, 100), true);
var figure = new PathFigure();
figure.Segments.Add(segment);
Figures = new PathFigureCollection();
Figures.Add(figure);
geometry.Figures = Figures;
}
public PathFigureCollection Figures { get; set; }
private void Canvas_MouseMove(object sender, MouseEventArgs e)
{
var firstSegment = Figures[0].Segments[0] as BezierSegment;
firstSegment.Point2 = e.GetPosition(sender as IInputElement);
}
}
Figures
显然,当您绑定属性时,对路径图的更新将不起作用。以下绑定将图形分配一次,但以后的更改不会反映在路径中。
// replace
// geometry.Figures = Figures;
// by
BindingOperations.SetBinding(geometry, PathGeometry.FiguresProperty,
new Binding
{
Path = new PropertyPath("Figures"),
Source = this
});