Search code examples
c#windowswindows-runtimewindows-store-appswindows-store

runtime Movable rectangle windows store app


I am trying to create runt time rectangle which will move on dragging by mouse. For some reason code is not working.

    private void Rectangle_Click(object sender, RoutedEventArgs e)
    {
        var rec = new Rectangle();
        rec.Height = 100;
        rec.Width = 100;
        rec.Fill = new SolidColorBrush(Colors.Violet);

        rec.ManipulationDelta += rec_ManipulationDelta;
        board.Children.Add(rec);

    }

    void rec_ManipulationDelta(object sender, ManipulationDeltaRoutedEventArgs e)
    {
        dragTranslation.X += e.Delta.Translation.X;
        dragTranslation.Y += e.Delta.Translation.Y;

        dragTranslation = new TranslateTransform();

        this.RenderTransform = this.dragTranslation;
    } 

Solution

  • The problem's when assigning the transforms. Try

    private void Rectangle_Click(object sender, RoutedEventArgs e)
    {
        var rec = new Rectangle();
        rec.Height = 100;
        rec.Width = 100;
        rec.Fill = new SolidColorBrush(Colors.Violet);
    
        rec.ManipulationMode=ManipulationModes.All;
        rec.ManipulationDelta += rec_ManipulationDelta;
        rec.RenderTransform=new TranslateTransform(); // Create new TranslateTransform and assign to the rectangle
        board.Children.Add(rec);
    
    }
    
    void rec_ManipulationDelta(object sender, ManipulationDeltaRoutedEventArgs e)
    {
        Rectangle recSender = (Rectangle) sender; // Get the Rectangle
        TranslateTransform ttSender = recSender.RenderTransform as TranslateTransform; // Get the Rectangle's RenderTransform (which is a TranslateTransform)
    
        ttSender.X += e.Delta.Translation.X;
        ttSender.Y += e.Delta.Translation.Y;
    
    }