c# - 拖放元素的位置 (MouseDragElementBehavior)

标签 c# wpf drag-and-drop

我正在尝试使用 MouseDragElementBehavior 实现具有拖放功能的 WPF 应用程序。 但是我就是找不到一种方法来获取相对于其父 Canavs 的放置元素的位置。 示例代码:

namespace DragTest {
    public partial class MainWindow : Window {

        private Canvas _child;

        public MainWindow() {
            InitializeComponent();

            Canvas parent = new Canvas();
            parent.Width = 400;
            parent.Height = 300;
            parent.Background = new SolidColorBrush(Colors.LightGray);    

            _child = new Canvas();
            _child.Width = 50;
            _child.Height = 50;
            _child.Background = new SolidColorBrush(Colors.Black);

            MouseDragElementBehavior dragBehavior = new MouseDragElementBehavior();
            dragBehavior.Attach(_child);
            dragBehavior.DragBegun += onDragBegun;
            dragBehavior.DragFinished += onDragFinished;

            Canvas.SetLeft(_child, 0);
            Canvas.SetTop(_child, 0);

            parent.Children.Add(_child);

            Content = parent;

        }

        private void onDragBegun(object sender, MouseEventArgs args) {
            Debug.WriteLine(Canvas.GetLeft(_child));
        }

        private void onDragFinished(object sender, MouseEventArgs args) {
            Debug.WriteLine(Canvas.GetLeft(_child));
        }
    }
}

在放下子 Canvas 之后,Canvas.GetLeft(_child) 的值仍然为 0。 为什么?为什么不改变?

当然,我可以使用dragBehavior.X 获取新位置,但那是子Canvas 在主窗口中的位置,而不是相对于父Canvas 的位置。一定有办法得到它...

最佳答案

我刚找到一个解决方法:

private void onDragFinished(object sender, MouseEventArgs args) {
    Point windowCoordinates = new Point(((MouseDragElementBehavior)sender).X, ((MouseDragElementBehavior)sender).Y); 
    Point screenCoordinates = this.PointToScreen(windowCoordinates);
    Point parentCoordinates = _parent.PointFromScreen(screenCoordinates);
    Debug.WriteLine(parentCoordinates);
}

所以我简单地将点转换为屏幕坐标,然后从屏幕坐标转换为父坐标。

然而,如果父 Canvas 在某些 ScrollView 或其他东西中,则会出现问题。 这种拖放方法似乎没有简单的解决方案...

关于c# - 拖放元素的位置 (MouseDragElementBehavior),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7295353/

相关文章:

c# 引用 a 使用继承自 c 的 b

c# - 如何使用 Gmail 的 SMTP 客户端在 C# 中向自己发送电子邮件,而无需在 Gmail 设置中启用对安全性较低的应用程序的访问?

c# - 什么更好 : id ? ? 0 == 0 或 id == null ||编号 == 0?

c# - 如何使用 WPF 创建平面组合框?

c# - Model/ViewModel 设计中的类继承错误

c# - 为什么我的 WindsorContainer 不能解析 IWindsorContainer?

wpf - 将控件绑定(bind)到两个属性

cocoa - 拖放粘贴板数据

javascript - 将 map 外部的内容拖放到要素(openlayers)上?

javascript - 看不到我使用 React-dnd 拖动的项目