DesignerProperties.GetIsInDesignMode_ForRealz [How to: Reliably detect Silverlight design mode in Blend and Visual Studio]
Catching up on Dave Campbell's fantastic WynApse feed earlier today, I came across this post by Bryant Likes about detecting design mode in Silverlight. One of the things mentioned in that post was the challenge of finding a design mode check that works correctly in both Expression Blend and Visual Studio's XAML designer. Unfortunately, the official mechanism for this, DesignerProperties.GetIsInDesignMode, doesn't always return the correct value under Visual Studio. :(
Well, I needed something reliable for the Charting assembly in the Silverlight Toolkit, so I checked with the experts (i.e., members of both teams) and came up with the following code that returns the correct value under both Blend and Visual studio (from DesignerProperties.cs in the Silverlight Toolkit source).
I present it here in the hope that others might also benefit:
/// <summary> /// Provides a custom implementation of DesignerProperties.GetIsInDesignMode /// to work around an issue. /// </summary> internal static class DesignerProperties { /// <summary> /// Returns whether the control is in design mode (running under Blend /// or Visual Studio). /// </summary> /// <param name="element">The element from which the property value is /// read.</param> /// <returns>True if in design mode.</returns> [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "element", Justification = "Matching declaration of System.ComponentModel.DesignerProperties.GetIsInDesignMode (which has a bug and is not reliable).")] public static bool GetIsInDesignMode(DependencyObject element) { if (!_isInDesignMode.HasValue) { _isInDesignMode = (null == Application.Current) || Application.Current.GetType() == typeof(Application); } return _isInDesignMode.Value; } /// <summary> /// Stores the computed InDesignMode value. /// </summary> private static bool? _isInDesignMode; }