2011-09-03 65 views
4

我试图通过使用MouseDragElementBehavior将&拖放功能实现WPF应用程序。 但我只是无法找到一种方式来获取相对于其父Canavs的下降元素位置。 示例代码:拖拽元素的位置(MouseDragElementBehavior)

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获得新的位置,但这是Canvas在子窗口中的位置,而不是相对于父Canvas的位置。必须有一种方式来获得它...

回答

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或某些东西中,则会出现问题。 似乎没有一个简单的解决方案,与此拖动&下降办法...