www.planet-xaml.net
[WPF]

Waiting until a template is loaded in WPF

by Florian Krüsch September 18, 2008

I ran into this while implementing a dialog inside a Popup. Popups are interesting, because they are part of the logical and visual tree, yet they render into a different HWND. Anyway, the problem was I needed to give the dialog keyboard focus when it opens, but at that time the control template isn't even expanded yet.

Looking at Ben Carters excellent ScrollViewer Preview ToolTip I found a neat way to handle this and wrapped it into an extension method:

C#toggle
public static class Extensions
{
   public static void InvokeWhenLoaded<T>(this T obj, Action action) 
      where T : DependencyObject
   {
      obj.Dispatcher.BeginInvoke(action, DispatcherPriority.Loaded);
   }
}
// Usage:
if (isOpen) 
   win.InvokeWhenLoaded(() => win._dialog.Focus());

Basically this adds the action into the Dispatcher Queue which will invoke it the next time the Dispatcher is finished loading controls. At this time the template is expanded and you can savely set focus on child elements.

If you thought Dispatcher.BeginInvoke is just about UI-thread marshalling you're as wrong as I was :)

Cheers,
Florian

 

No comments

Language | Sprache

All[e]  |  english  |  deutsch
Tags
 

Profile

Florian Kruesch

I am working as a freelance software architect, developer and consultant in Düsseldorf, Germany.

My focus is on Microsoft technologies and .NET 3.0, especially WPF, ASP.net and SQL Server.

I've been a lead programmer on the WPF development of the OTTO Vista Store at SinnerSchrader Studios.

My client list includes DHL, LG and Ogilvy Interactive.