Andrej Tozon's blog

In the Attic


Countdown to Silverlight 3 #5: ChildWindow (Modal, Non-modal, Templated)

There are many controls being introduced in Silverlight 3; a lot of them were pulled from the Silverlight Toolkit (the idea is that for every new Silverlight version, Toolkit controls marked as stable are moved to the Silverlight core. I’m not sure how many new controls I’m going to cover in this series, but the ChildWindow definitely deserves a separate post and sample.

ChildWindow is a special control, which behaves like a dialog. By default, it is set up to display itself as a modal dialog and can be easily re-templated to give it a new look (included in the sample below).

There are three steps required to make the ChildWindow display as a non-modal (floating) window:

1. Create a copy of the default template and get rid of all animations, referencing the Overlay element. The overlay covers all area “behind” the child window and makes it look disabled. If you remove the Overlay element itself, the window will not be centered on the screen when invoked, so it’s best to keep it in, but somehow hide it.

<Grid x:Name="Overlay" Width="0" Height="0" />

2. This is a hack. ChildWindow disables the root element when invoked so you have to re-enable it when window is shown:

Control root = Application.Current.RootVisual as Control;
if (root != null)
root.IsEnabled = true;

3. This is a hack. ChildWindow also takes control of re-focusing the window when the root control gains the focus so we have to hack into the ChildWindow’s LostFocus event to take care of this:

protected override void OnLostFocus(RoutedEventArgs e)
LostFocus -= Delegate.CreateDelegate(typeof(RoutedEventHandler), this,
    "ChildWindow_LostFocus") as RoutedEventHandler;

Additional reading: (a better approach to non-modal window, also read the comments)

Run the sample below

Source code below: