Design Time Check for WPF and Silverlight
Do you commonly check whether code is being run in Blend or in the Visual Studio design surface? Often times, this is necessary to load up sample data or to prevent code that could potentially break the “Blendability” of a WPF or Silverlight app.
In WPF, you can call the DesignerProperties.GetIsInDesignMode for it. In Silverlight, you can check for HtmlPage.IsEnabled property.
I check for design mode often and needed a simple, consistent method to mask the DesignerProperties call in WPF. In Silverlight, I wanted to hide the hacky HtmlPage.IsEnabled check and change it from being a not(!) check to a positive check. Also, when Silverlight support the DesignerProperties.GetIsInDesignMode method, I can just easily change my check in one place. With some refinements from friends at work, I condensed it to a single static property in App.xaml.cs that I can use throughout my application.
In App.xaml.cs:
public static bool IsInDesignMode
{
get
{
#if Silverlight
return !HtmlPage.IsEnabled;;
#else
return DesignerProperties.GetIsInDesignMode(new DependencyObject());
#endif
}
}
Note that the precompiler directives can be removed if you’re just targeting WPF or just targeting Silverlight
Here’s how I use it:
void MainView_Loaded(object sender, RoutedEventArgs e)
{
if (App.IsInDesignMode)
{
LoadSampleData();
}
else
{
LoadRunTimeData();
}
}

What about making that an extension method of some sort, did you try that?
You can also provide design-time support that might work for the case of loading sample data; check out DesignModeValueProvider http://is.gd/jbXb
It’s not a solution for behaviors that might break the designer, but it would let you substitute some dummy data for the data that’s configured at design-time.
Keith, interesting point. You’re right, I can probably do this as an extension method for the WPF window class.
Owen, I haven’t encountered the DesignModeValueProvider before. definitely going to read up on it now.
The problem with using HtmlPage.IsEnabled in Silverlight is that many times if you’re using a hosted xap or have turned off html access then you’ll end up in design mode even when you’re not. Seems like there must be a better way, but I still haven’t found it.
Bryan, I agree. But currently that’s the only way that I’ve found to work. By encapsulating it in one area, I’m hoping to minimize the changes that I need to make when there is a better way to detect design mode.
Application.Current will be null if in Visual Studio
@Steve Drake
That works very nicely
Simple and easy, tanks