我试图使用WPF模拟一种简单的类似CAD的行为,其中多边形被绘制到画布上,并且多边形的点可以移动。
我设法得到它,以便通过为集合中的每个Point设置一个带有Ellipse的ItemsControl,在画布上显示PointCollection属性。多边形正确显示,因此我知道Binding正在使用Source-To-Target。我已经设置了一些简单的活动,以便能够选择'多边形的点,并移动它们。事件工作正常,多边形确实在画布上发生变化。但是,我对点位置所做的任何更改都不会被推送到源属性。
有关如何让Binding在相反方向上工作的任何线索?这种事情(ItemsControl中的双向绑定)是否可能?或许还有另一种方法!
由于
XAML
<Canvas Width="500" Height="300" MouseMove="MoveMouse">
<ItemsControl ItemsSource="{Binding Path=MyPath, Mode=TwoWay, NotifyOnSourceUpdated=True }">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Canvas>
<Ellipse Width="20"
Height="20"
Canvas.Left="{Binding Path=X, Mode=TwoWay, NotifyOnSourceUpdated=True }"
Canvas.Top="{Binding Path=Y, Mode=TwoWay, NotifyOnSourceUpdated=True }"
Fill="Red"
Margin="-10,-10,0,0"
MouseDown="ClickPoint" />
</Canvas>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Canvas>
MainWindow.cs
public partial class MainWindow : Window
{
public PointCollection MyPath { get; set; } = new PointCollection{ new Point(10, 10), new Point(100, 100), new Point(200, 100) };
public Ellipse selectedPoint;
public MainWindow()
{
InitializeComponent();
}
private void MoveMouse(object sender, MouseEventArgs e)
{
if (selectedPoint == null) return;
//Move selected point to mouse position
selectedPoint.SetValue(Canvas.LeftProperty, e.GetPosition(sender as UIElement).X);
selectedPoint.SetValue(Canvas.TopProperty, e.GetPosition(sender as UIElement).Y);
//Print out MyPath points to check if source has changed
Console.WriteLine("");
foreach (Point p in MyPath)
Console.Write(p + " - ");
}
private void ClickPoint(object sender, MouseButtonEventArgs e)
{
//Pick up point, if no point is currently selected
selectedPoint = selectedPoint == null ? (Ellipse)sender : null;
}
}