Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to position a popup control in a Windows Store App relative to a button?

After clicking on a button in a Windows Store App a Popup Control should be displayed near to the button.

Positioning the Popup using its VerticalOffset and HorizontalOffset properties (== coordinates relative to top left corner) is no problem, but how do I get the position of the button relative to the screen to calculate the offsets correctly?

The button is located somewhere on a page and does not have a fixed position relative to the screen (e.g. when placed in a scroll view, etc.). How do I get the button's coordinates?

like image 915
Andrei Herford Avatar asked Feb 27 '14 10:02

Andrei Herford


1 Answers

You need to use these calls: UIElement.TransformToVisual and GeneralTransform.TransformPoint. Unfortunately, it has been a while since I did this so I can't give more specifics on what exactly these calls do.

The code below figures out the upper left position of the button and opens the popup there. You will probably want to adjust the positioning depending on your needs.

private void btnClickMe_Click(object sender, RoutedEventArgs e)
{
    Popup popUp = new Popup();
    // TODO: Add your elements to the popup here...

    // open the popup at the same coordinates as the button
    var point = CalcOffsets((UIElement)sender);
    popUp.HorizontalOffset = point.X;
    popUp.VerticalOffset = point.Y;

    popUp.IsOpen = true;
}

private Point CalcOffsets(UIElement elem)
{
    // I don't recall the exact specifics on why these
    // calls are needed - but this works.
    var transform = elem.TransformToVisual(this);
    Point point = transform.TransformPoint(new Point(0, 0));

    return point;
}
like image 84
chue x Avatar answered Nov 02 '22 23:11

chue x