Search code examples
c#wpftransformuielement

WPF - How to move a UIElement dynamically


I have an ellipse inside a grid and I want to move the ellipse.

I have tried to use RenderTransform.Transform() and TranslatePoint() but nothing happened, on the latter I tried to set the parameter relativeTo to the ellipse and to grid but I get no movement nor exceptions in either case.

Attempts:

ellipse.RenderTransform.Transform(position);
//or
ellipse.TranslatePoint(position, grid);
//or
ellipse.TranslatePoint(position, ellipse);

What should I use to move the ellipse in my scenario?

Edit: On Xamarin I use the TranslationY property that allows me to do what I want, the docs tell me to use TranslateTransform but I dont understand how to use it.


Solution

  • Assign a TranslateTransform to the Ellipse's RenderTransform property

    Thanks Clemens to point that out in the comment section

    myUIElement.RenderTransform = new TranslateTransform(50,50);
    

    Offsets the UIElement 50 units right and down

    If its required to move several times its possible to use X and Y properties of TranslateTransform.

    TranslateTransform position = new();
    
    public void MoveRight(double _x)
    {
       position.X += _x;
       myUIElement.RenderTransform = position;
    }
    

    MoveRight() offsets the UIElement x axis by _x units