WPF: How to get the bounds of a control in an automatic layout container, in the container coordinate space

Googling this the other day, I started to get the impression that this might be annoyingly tricky. You might wonder why this is necessary at all, given that WPF implements layout for you in most cases (except for containers such as Canvas), but trust me, if you’re developing custom elements, at some point you’re probably going to need it.

If you’re adding controls to a Canvas you can always use the attached Left, Right, etc., properties to get the bounds. Fortunately it’s really no more difficult when using a container that implements automatic layout, such as StackPanel either. Before I go any further though, I should point out that the code in this post will not work for Silverlight. This is because the Silverlight VisualTreeHelper class doesn’t implement the GetOffset method, which is available in the version of VisualTreeHelper that ships with the full .NET Framework from 3.5 onwards. Obviously this doesn’t matter if you’re never going to deploy to Silverlight, but if you’re developing controls that might be used in both WPF and Silverlight apps, you might want to look for an alternative solution.

Pretty simple, right?

The one gotcha is that if you call this immediately after adding a control to its parent, before the layout has been updated, you’ll get (0, 0, 0, 0) in the Rect. To fix this you need to force a layout update by calling UpdateLayout on the parent control.

Until next time.