Friday, September 5, 2008

Silverlight Tip 1#: How to find the absolute position of any control ?

For the past few weeks I've been working on Silverlight project, a prototype business application. So I'm going to write some posts about resolving practical problems with Silverlight 2.

I've written custom control with popup like combobox or listbox (see below).

<StackPanel x:Name="LayoutRoot" Height="Auto">
<TextBox x:Name="DropDownTextBox" />
<Popup x:Name="DropDownListPopUp">
<ListBox x:Name="DropDownListBox"
Style="{StaticResource DropDownListBoxStyle}"
ItemContainerStyle="{StaticResource DropDownListBoxItemStyle}"
ItemTemplate="{StaticResource DropDownDataTemplate}"

How to display popup directly below the textbox? In order to do this you must get absolute position of the control on form:

GeneralTransform gt = this.TransformToVisual(Application.Current.RootVisual as UIElement);
Point offset = gt.Transform(new Point(0, 0));

and set VerticalOffset and HorizontalOffset properties of popup:

DropDownListPopUp.VerticalOffset = offset.Y + this.DropDownTextBox.ActualHeight;
DropDownListPopUp.HorizontalOffset = offset.X;

Finally, you display popup:

DropDownListPopUp.IsOpen = true;


Rafael Veras said...

Hey guy,

you are the man!

this tip is exactly what I was looking for.

Thank you!

liviu said...

If the browser zoom is different then 100% it is useful to take the App.Current.Host.Content.ZoomFactor into consideration to position the popup correctly.