加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 21:23:19 所属栏目:百科 来源:网络整理
导读:我正在尝试使用MouseDragElementBehavior实现具有拖放功能的 WPF应用程序. 但我找不到相对于其父Canavs获取被删除元素位置的方法. 示例代码: namespace DragTest { public partial class MainWindow : Window { private Canvas _child; public MainWindow()
我正在尝试使用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方法似乎没有一个简单的解决方案……

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读