如何在WPF中的Canvas控件中拖动和移动自定义控件 [英] How to drag and move Custom Control inside Canvas control in WPF
问题描述
我创建了一个自定义Circle控件并添加到画布控件中,如下面的代码:(注意: - 主窗体有一个按钮控件。它将动态地在Canvas控件中创建一个圆控件。)
_panel.Children.Add(_circle);
现在我需要在Canvas控件中实现拖动和移动功能。我尝试使用以下代码实现:
Circle.xmal.cs
I have created a custom Circle control and added in to a canvas control like following code: (Note:- The main form has a button control. It will create a circle control inside Canvas control dynamically.)
_panel.Children.Add(_circle);
Now I need to implement drag and move functionality inside the Canvas control. I have tried to implement using the following code:
Circle.xmal.cs
protected void shape_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
xMouseLeftButtonDown(sender, e);
}
protected void shape_MouseMove(object sender, MouseEventArgs e)
{
xMouseMove(sender, e);
}
protected void shape_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
xMouseLeftButtonUp(sender, e);
}
Main.xaml.cs
Main.xaml.cs
protected void shape_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
source = (UIElement)sender;
Mouse.Capture(source);
captured = true;
x_shape = Canvas.GetLeft(source);
x_canvas = e.GetPosition(LayoutRoot).X;
y_shape = Canvas.GetTop(source);
y_canvas = e.GetPosition(LayoutRoot).Y;
}
protected void shape_MouseMove(object sender, MouseEventArgs e)
{
if (captured)
{
double x = e.GetPosition(LayoutRoot).X;
double y = e.GetPosition(LayoutRoot).Y;
x_shape += x - x_canvas;
Canvas.SetLeft(source, x_shape);
x_canvas = x;
y_shape += y - y_canvas;
Canvas.SetTop(source, y_shape);
y_canvas = y;
}
}
protected void shape_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
Mouse.Capture(null);
captured = false;
}
但它不起作用。任何人都可以建议我如何实现这一点。
But its not working. can anyone suggest me how to implement this.
推荐答案
请阅读我对这个问题的评论。
看看这里:拖放WPF控件 [ ^ ]
Please read my comment to the question.
Have a look here: Drag and drop WPF controls[^]
这篇关于如何在WPF中的Canvas控件中拖动和移动自定义控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!