TranslateTransform for drag and drop in Silverlight

Posted by fuzzyman on Stack Overflow See other posts from Stack Overflow or by fuzzyman
Published on 2010-03-22T19:17:26Z Indexed on 2010/03/22 19:21 UTC
Read the original article Hit count: 369

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?

© Stack Overflow or respective owner

Related posts about Silverlight

Related posts about draganddrop