微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我正在尝试使用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或somthing中会出现问题.这种Drag& Drop方法似乎没有一个简单的解决方案……

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐