Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the position of an element in a StackPanel?

Say I have a StackPanel that gets dynamically filled with copy, changing the Y position of elements inside it. I have a specific element within that StackPanel that I want to find the Y position of (relative to the StackPanel or otherwise) after the StackPanel is done repositioning all of it's children.

StackPanel sp = new StackPanel();
sp.Children.Add(someTextBlock);
sp.Children.Add(element1);
sp.Children.Add(element2);
...
someTextBlock.Text = "Lorem ipsum dolor..." // some text that pushes children of > index down
// element1 got pushed down to some unknown position based on text length
// now want to find the Y position of element1

I noticed that methods like this: http://forums.silverlight.net/forums/p/16787/55881.aspx#55881 don't work since the position returned is the position of the StackPanel and not the child element I'm targeting.

like image 902
roblocop Avatar asked Oct 02 '09 16:10

roblocop


2 Answers

The methods in the link you posted should work fine, provided you call them correctly.

You need to call them with the correct UIElement - in this case, using element1 to the RootVisual will give you the full position of element1:

var transform = element1.TransformToVisual(Application.Current.RootVisual as FrameworkElement);        
Point absolutePosition = transform.Transform(new Point(0, 0));
like image 84
Reed Copsey Avatar answered Nov 02 '22 14:11

Reed Copsey


A small note to Reed's answer.

My UserControl has a StackPanel. It didn't work for me when I called it in

private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
    sp.Children.Add(someTextBlock);
    sp.Children.Add(element1);
    sp.Children.Add(element2);

    var transform = element1.TransformToVisual(Application.Current.RootVisual as FrameworkElement);        
    Point absolutePosition = transform.Transform(new Point(0, 0));
}

It work when I call it in

 private void UserControl_LayoutUpdated(object sender, EventArgs e)
        {
         ...
        }

I hope it helps to someone.

like image 1
Eugene Avatar answered Nov 02 '22 15:11

Eugene