KentZhou
KentZhou

Reputation: 25573

How to position popup in click event with silverlight 4?

I try to use link button click event to create a popup with some data list.but the default position of popup is top-left of the whole browser window.

It seems different control need different way to position popup. like Image control with LeftButtondown/up event would be different from click event for button/link button.

How to set the popup position right under the link button?

Upvotes: 4

Views: 6763

Answers (1)

AnthonyWJones
AnthonyWJones

Reputation: 189487

There are two approaches.

Option 1

You can position a popup via its HorizontalOffset and VerticalOffset properties. You just need to workout what values to set them to. Like this:-

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        Popup popup = new Popup();
        Button b = (Button)sender;
        GeneralTransform gt = b.TransformToVisual(Application.Current.RootVisual);
        Point p = gt.Transform(new Point(0, b.ActualHeight));

        popup.HorizontalOffset = p.X;
        popup.VerticalOffset = p.Y;
        popup.Child = new Border()
        {
            Child = new TextBlock() { Text = "Hello, World!" },
            Background = new SolidColorBrush(Colors.Cyan)
        };
    }

Here we use the TrannsformToVisual method of the button to get a transform relative to the application root visual which has the same origin that the popup will have. Using the buttons actual height we can arrive at a point at the bottom left corner of the button.

Option 2

An alternative is place the Popup in the layout.

 <StackPanel>
     <Button Content="Click Me" Click="Button_Click" />
     <Popup x:Name="popup" />
     <TextBlock Text="This text will be occluded when the popup is open" />
 </StackPanel>

code:-

    private void Button_Click(object sender, RoutedEventArgs e)
    {

        popup.Child = new Border()
        {
            Child = new TextBlock() { Text = "Hello, World!" },
            Background = new SolidColorBrush(Colors.Cyan)
        };

        popup.IsOpen = !popup.IsOpen;
    }

In this approach the origin of the Popup is placed by the layout system, in this case we have used a StackPanel so the popup is placed directly below the button. However the popup doesn't take up any space in the layout so the textblock appears immediately below the button.

Upvotes: 11

Related Questions