如何在WPF中的Canvas控件中拖动和移动自定义控件
问题描述:
我创建了一个自定义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.