Checking for Design Time in Silverlight Applications
Occasionally, you’ll want to alter your application logic to behave different when in design mode. (E.g., when you’re viewing your application in Blend or Visual Studio "Cider”.) Usually, you’ll want to alter your application to use mock data sources and perhaps skip out on validation, user prompts, etc..
So how do you check for design time? Easy! Use the DesignerProperties.GetIsInDesignMode(…) method and it’ll return ‘true’ if your application is currently hosted by a designer.
Works great for Blend. Unfortunately, this currently does not work with Cider. (Cider, btw, is the designer surface you see in Visual Studio.) I’ve found it useful to create my own application-level property to provide hints about design time to work around the Cider issue.
I’ve created a static Boolean property that uses DesignerProperties.GetIsInDesignMode(…) first (because it does work in Blend) and falls back to examining the current Application instance. This works because the Application instantiated during design time is, for the time being, either nothing or of type Application.
public static bool InDesignMode
{
get
{
if (inDesignMode.HasValue == false)
{
inDesignMode =
Application.Current == null ||
Application.Current.GetType() == typeof(Application);
}
return inDesignMode.Value;
}
}
Simple enough and it gets the job done. :) That said, this will probably be scrapped in Visual Studio 2010 when we get a better XAML editor … I hope.
If you want to see this working in a real designer, don’t forget that you can open up another instance of Visual Studio (or your favorite debugger) and attach to VS/Blend/<whatever> and set your breakpoints to watch how your application really behaves while in design mode. Very useful!
Debugging Silverlight in Firefox, Safari
If you’re already familiar with attaching to processes in Visual Studio (or WinDbg), this is nothing new. However, I’ve seen this question come up a few times—particularly with people coming over from competing technologies.
In Visual Studio, just select the “Attach to process” option (available in the Debug or Tools menu, depending on your workspace view) and select the type of code you want to debug, Silverlight in this case, and the process you want to debug. This applies to any process that is hosting a Silverlight instance.
You should be aware that this general advice applies to all sorts of applications. For example, if you want to debug the behavior of your Silverlight control library during design-time operations, you could use one instance of the debugger to attach to the application that is rendering the design surface. (E.g., attach to Blend or event to another instance of Visual Studio.)