locked
Drag and Drop between two Canvas

    Question

  • How to drag and drop an Rectangle for example between two canvas controls?
    I am using a ManipulationDelta event. But, after ManipulationCompleted I don't know how to detect that I raised a finger on another Canvas.

    I tried the following:

    <Grid Name="MainGrid" PointerMoved="Rectangle_PointerMoved" Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
    
        <Canvas Name="Canv0" Background="Gray" Grid.Column="0">
            <Border
                Width="80" 
                Height="80" 
                Background="Red" 
                Canvas.Left="100" 
                Canvas.Top="100" 
                ManipulationDelta="Border_ManipulationDelta"
                ManipulationMode="TranslateX , TranslateY" 
                ManipulationCompleted="Border_ManipulationCompleted"
                />
        </Canvas>
        <Canvas Name="Canv1" Background="LightGray"  Grid.Column="1"></Canvas>
    </Grid>

    private void Border_ManipulationDelta(object sender, ManipulationDeltaRoutedEventArgs e)
    {
        Border myBorder = (Border)sender;
        Canvas.SetLeft(myBorder, Canvas.GetLeft(myBorder) + e.Delta.Translation.X);
        Canvas.SetTop(myBorder, Canvas.GetTop(myBorder) + e.Delta.Translation.Y);
    }
    
    private void Border_ManipulationCompleted(object sender, ManipulationCompletedRoutedEventArgs e)
    {
        Border myBorder = (Border)sender;
        var position = myBorder.TransformToVisual(Window.Current.Content).TransformPoint(new Point());
        var elements = VisualTreeHelper.FindElementsInHostCoordinates(position, MainGrid);
        foreach (UIElement element in elements)
        {
            if (element is Canvas)
            {
                // code
            }
        }
    }

    But when you drag to another canvas element (Border) occurs hiding under him. I do not know how to fix it. Not sure that it is generally the right approach.

    • Edited by Riccon2 Sunday, February 09, 2014 7:01 AM
    Sunday, February 09, 2014 6:58 AM

Answers

  • Pull your Border outside of the first canvas before dragging it and place it at the top of the z-order so it is above the second Canvas.

    As is your code changes the position only within the first Canvas. Translating by adjusting the RenderTransform rather than the Canvas.Left and Top properties will be much more efficient and will be relevant outside of the original Canvas.

    --Rob

    • Marked as answer by Riccon2 Saturday, February 15, 2014 3:52 PM
    Monday, February 10, 2014 3:21 AM
    Owner