views:

422

answers:

1

We're trying to implement drag and drop in Silverlight (3). We want users to be able to drag elements from a treeview onto another part of a UI. The parent element is a Grid, and we've been trying to use a TranslateTransform along with the MouseLeftButtonDown, MouseMove (etc) events, as recommended by various online examples. For example:

http://www.85turns.com/2008/08/13/drag-and-drop-silverlight-example/

We're doing this in IronPython, but that should be more or less irrelevant. The drag start is correctly initiated, but the item we are dragging appears in the 'wrong' location (offset a few hundred pixels to the right and down from the cursor) and I can't for the life of me work out why.

Basic xaml:

<Grid x:Name="layout_root">
    <Grid.RowDefinitions>
        <RowDefinition/>
        <RowDefinition Height="120"/>
    </Grid.RowDefinitions>
    <Border x:Name="drag" Background="LightGray" Width="40" Height="15"
     Visibility="Collapsed" Canvas.ZIndex="10">
        <Border.RenderTransform>
            <TranslateTransform x:Name="transform" X="0" Y="0" />
        </Border.RenderTransform>            
        <TextBlock x:Name="dragText" TextAlignment="Center"
         Foreground="Gray" Text="foo" />
    </Border>
    ...
</Grid>

The startDrag method is triggered by the MouseLeftButtonDown event (on a TextBlock in a TreeViewItem.Header). onDrag is triggered by MouseMove. In the following code self.root is Application.Current.RootVisual (top level UI element from app.xaml):

def startDrag(self, sender, event):
    self.root.drag.Visibility = Visibility.Visible
    self.root.dragText.Text = sender.Text
    position = event.GetPosition(self.root.drag.Parent)

    self.root.drag.transform.X = position.X
    self.root.drag.transform.Y = position.Y

    self.root.CaptureMouse()
    self._captured = True

def onDrag(self, sender, event):
    if self._captured:
        position = event.GetPosition(self.root.drag.Parent)
        self.root.drag.transform.X = position.X
        self.root.drag.transform.Y = position.Y

The dragged item follows the mouse move, but is offset considerably. Any idea what I am doing wrong and how to correct it?

A: 

So it turns out that I should have been setting the Margin instead of using TranslateTransform:

def startDrag(self, sender, event):
    self.root.drag.Visibility = Visibility.Visible
    self.root.dragText.Text = sender.Text

    self.root.CaptureMouse()
    self._captured = True
    self.root.MouseLeftButtonUp += self.stopDrag
    self.root.MouseLeave += self.stopDrag
    self.onDrag(sender, event)

def onDrag(self, sender, event):
    if self._captured:
        position = event.GetPosition(self.root.layout_root)
        self.root.drag.Margin = Thickness(position.X, position.Y, 0, 0)
        self.root.drag.UpdateLayout() 
fuzzyman