WPF - How to move a UIElement dynamically

519 Views Asked by At

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.

2

There are 2 best solutions below

0
Barreto On BEST ANSWER

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

3
mm8 On

Put the Ellipse in a Canvas and control its position using the attached Canvas.Left and Canvas.Top properties or, using your current approach, use the Margin property to position it inside the Grid.

Here is an example.

private void Button_Click(object sender, RoutedEventArgs e)
{
    var margin = ellipse.Margin;
    ellipse.Margin = new Thickness(margin.Left, margin.Top + 10, margin.Right, margin.Bottom);
}

XAML:

<Grid x:Name="GrFrame">
    <Grid.RowDefinitions>
        <RowDefinition Height="*" />
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>
    <Ellipse x:Name="ellipse" Width="100" Height="100" Fill="Red" VerticalAlignment="Center" HorizontalAlignment="Center" />
    <Button Grid.Row="1" Content="Move down" Click="Button_Click" />
</Grid>