我有Canvas
我正在绘制形状。
我添加了一个矩形,可以轻松添加拖动选项:
<Canvas>
<Rectangle Width="100" Height="50" Canvas.Left="197" Canvas.Top="131" Fill="Red" >
<i:Interaction.Behaviors>
<il:MouseDragElementBehavior/>
</i:Interaction.Behaviors>
</Rectangle>
</Canvas>
我希望自动完成所有这些。所以,我将xaml
更改为:
<ItemsControl ItemsSource="{Binding CanvasItems, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
在ViewModel
:
private ObservableCollection<Shape> m_canvasItems = new ObservableCollection<Shape>();
public ObservableCollection<Shape> CanvasItems
{
get => m_canvasItems;
set
{
m_canvasItems = value;
OnPropertyChanged();
}
}
public MainWindowViewModel()
{
var newRect = new Rectangle
{
Width = 100,
Height = 50,
Fill = Brushes.Red
};
Canvas.SetLeft(newRect, 197);
Canvas.SetTop(newRect, 131);
CanvasItems.Add(newRect);
}
在同一namespace
下,我也有这个课程:
public class DragBehavior : Behavior<UIElement>
{
public Point ElementStartPosition { get; private set; }
private Point mouseStartPosition;
private readonly TranslateTransform transform = new TranslateTransform();
protected override void OnAttached()
{
var parent = Application.Current.MainWindow;
AssociatedObject.RenderTransform = transform;
AssociatedObject.MouseLeftButtonDown += (sender, e) =>
{
ElementStartPosition = AssociatedObject.TranslatePoint(new Point(), parent);
mouseStartPosition = e.GetPosition(parent);
AssociatedObject.CaptureMouse();
};
AssociatedObject.MouseLeftButtonUp += (sender, e) => { AssociatedObject.ReleaseMouseCapture(); };
AssociatedObject.MouseMove += (sender, e) =>
{
var diff = e.GetPosition(parent) - mouseStartPosition;
if (!AssociatedObject.IsMouseCaptured) return;
transform.X = diff.X;
transform.Y = diff.Y;
};
}
}
所以现在我希望实现我在第一个xaml
中所做的事情 - 使用Rectangle
类从后面的代码中添加一个拖动选项到我动态创建的DragBegavior
。
这件事可以实现吗?