Silverlight ChildWindows and VisualStates

Unfortunately, as of the latest version of Silverlight 4 and Blend 4, there’s a feature supportability mismatch. Blend 4’s designer may lead to you to believe and expect that VisualStates will work within a Silverlight 4 application. (It led me down that path).

In fact, VisualStates do not work directly inside of a ChildWindow. VisualStates are only applicable on the root element of a ControlTemplate or UserControl (as described here). I just spent the last 20 minutes learning about this limitation the hard way – by trying it, over and over. :)  It’s not a bug, it just isn’t supported.

If you want to use VisualStates within a ChildWindow, the simplest workaround for this problem is to wrap the content of the child window into a new UserControl and place that UserControl in the ChildWindow (as a child). You’ll need to do a little more work to expose the functionality of the UserControl to the containing ChildWindow (like OK/Cancel button handling for example), but it’s simple work. I added an event which indicates the child window should be closed:

public event EventHandler<CloseDialogEventArgs> CloseDialog;
public class CloseDialogEventArgs : EventArgs
{
    public bool? DialogResult { get; set; }

    private CloseDialogEventArgs()
    {

    }
    public CloseDialogEventArgs(bool? dialogResult)
    {
        DialogResult = dialogResult;
    }

    public static new CloseDialogEventArgs Empty = new CloseDialogEventArgs();
}

Then, it can be closed:

private void CancelButton_Click(object sender, RoutedEventArgs e)
{
    if (CloseDialog != null)
    {
        CloseDialog(this, new CloseDialogEventArgs(false));
    }
}