Nollie
Nollie

Reputation: 151

WPF changing position of an object

do you know any way to assign new position to element after some kind of action(e.g. pressing buton)?

Lets assume that in my WPF I have Rectangle named "Windajo" and I want to change its Y position to be actual_Y_position + 10.

I don't have a clue how to get actual position and only funtion that I managed to change position with is Margin. Many people are reffering to Canvas but I couldn't make it work.

I managed to change object position with Margin but it's (I guess) distance from MainWindow border and using it is kinda annoying.

private async void button_Click(object sender, RoutedEventArgs e)
        {
    int i = 300;

                do
                {
                    Windajo.Margin = new Thickness(85, i, 80, 0);
                    await Task.Delay(500);
                    i = i - 20;
                } while (i > 100);

        }

If reffering to last position is impossible, is there any way to get a actuall value from Thickness function? For example I want to assign "85" from Thickness (85, i, 80, 0). to some variable. How to do so?

I would like to do it inside code, like the example above.

I really appreciate any help you can provide :)

Upvotes: 2

Views: 2717

Answers (2)

Fᴀʀʜᴀɴ Aɴᴀᴍ
Fᴀʀʜᴀɴ Aɴᴀᴍ

Reputation: 6251

You can access individual components of the Thickness structure like this:

Windajo.Margin = new Thickness(85, i, 80, 0);
Thickness t = Windajo.Margin;
double left = t.Left;
double top = t.Top;
double right = t.Right;
double bottom = t.Bottom;

If you want to increase Y by 10, you need to decrease the Top margin by 10 if it is Top Aligned or increase the Bottom margin by 10 if it is Bottom Aligned:

Windajo.Margin = new Thickness(85, i - 10, 80, 0); // If Top-Aligned
// -- OR --
Windajo.Margin = new Thickness(85, i - 10, 80, 0); // If Bottom-Aligned

Upvotes: 0

dionesf
dionesf

Reputation: 187

You can take the actual value like this:

Windajo.Margin.Left 
Windajo.Margin.Right

And to this:

Windajo.Margin = new Thickness(85, Windajo.Margin.Top + 10, 80, 0);

Upvotes: 2

Related Questions