views:

134

answers:

1

Hi folks,

On my quest to implement a very simple 'drag' mechanism to my application (which consists of multiple canvasses nested inside a 'parent' canvas) I've come up with the following bits of code:

(Showing only the relevant bits to save space)

MainWindow.xaml

    <Canvas Name="parentCanvas" Background="#FFE8CACA">
        <Canvas Name="myCanvas" Height="100" Width="200" Background="#FFB4FFB4">
            <Thumb Name="myThumb" Canvas.Left="0" Canvas.Top="0" Background="Blue" Width="200" Height="20" DragDelta="onDragDelta" />
        </Canvas>

        <!-- debug -->
        <Button Content="Zero" Height="51" Name="button1" Width="46" Click="button1_Click" Canvas.Left="14" Canvas.Top="302" />
        <Label Name="pos" Width="499" Canvas.Left="77" Canvas.Top="302" Height="26" />
        <Label Name="changes" Height="28" Canvas.Left="77" Canvas.Top="325" Width="499" />
    </Canvas>

MainWindow.xaml.cs

    void onDragDelta(object sender, DragDeltaEventArgs e)
    {
        Canvas.SetLeft(myCanvas, e.HorizontalChange);
        Canvas.SetTop(myCanvas, e.VerticalChange);

        //debug info
        pos.Content = "Left: " + Canvas.GetLeft(myCanvas) + ", Top: " + Canvas.GetTop(myCanvas);
        changes.Content = "Horizontal: " + e.HorizontalChange + ", Vertical: " + e.VerticalChange;
    }

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        Canvas.SetLeft(myCanvas, 0);
        Canvas.SetTop(myCanvas, 0);
    }

Which seems to work, randomly! It seems to follow the mouse movements but I am having trouble interpreting the DragDeltaEventArgs, which causes a very unstable movement of the canvas. It's kind of hard to explain so here is a short video I've captured of it: http://img84.imageshack.us/img84/6614/drag.mp4

Any comments/suggestions will be much appreciated as I've been staring at this for a while and can't figure out what to do with it :(

Thanks,
Hamza.

+2  A: 

The Horizontal and Vertical changes are the amount moved since the previous event so you need to add them to the current position.

Canvas.SetLeft(myCanvas, Canvas.GetLeft(myCanvas) + e.HorizontalChange);
Canvas.SetTop(myCanvas, Canvas.GetTop(myCanvas) + e.VerticalChange);

You also need to set a starting position for the canvas otherwise you get NaN.

<Canvas Name="myCanvas" Height="100" Width="200" Background="#FFB4FFB4" Canvas.Left="0" Canvas.Top="0">
Kris
I get it now, thanks a lot for the explanation :)
Hamza