首页 文章

拖放元素的位置(MouseDragElementBehavior)

提问于
浏览
4

我正在尝试使用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.GetLeft(_child) 的值仍为0.为什么?为什么不改变?

当然,我可以通过使用 dragBehavior.X 来获取新位置,但是在主窗口中的's the child Canvas'位置,而不是相对于父Canvas的位置 . 必须有办法让它...

1 回答

  • 1

    我找到了一个解决方法:

    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中会出现问题 . 这种拖放方法似乎没有一个简单的解决方案......

相关问题