One of the things I’ve been trying to getting a better understanding of is how to make the Silverlight projects I work on more blendable:
In general, WPF and Silverlight controls should be "blendable". ItemsControls need to display representative data within the design surface.
The problem, at least for me, is that every example out there to detect design mode uses:
var designMode = !HtmlPage.IsEnabled;
Since the Html Bridge is disable inside of Blend, this does work for the most part, but what about when your xap is hosted on another server? In this case the Html Bridge is disabled by default so if someone doesn’t configure it correctly they will get your design time data.
* This can be changed to true, but it is disabled by default. ** Enabled by default
So I was trying to come up with another method to detect design mode in Silverlight and here is the best I have come up with so far:
public bool IsDesignTime() { try { var host = Application.Current.Host.Source; return false; } catch { return true; } }
What happens is that Application.Current.Host.Source works great when the plugin is hosted in a web page and will return the path to the xap file, but in design mode trying to access that property throws an exception. So if you hit the exception then you’re in design mode, otherwise you’re in a web page. Not super elegant but it feels better to me than checking if the Html Bridge is enabled since that isn’t a true check.
Update: As Tom mentions in the comments, you can also use DesignerProperties.GetIsInDesignMode. But if your goal is to make your project more blendable then Visual Studio support might not be important.
So with this check worst case you get no data in the Visual Studio designer, but the Visual Studio designer isn’t that great anyway. Blend is the real goal. So instead instead of the above code you can use this code instead:
public bool IsDesignTime() { return DesignerProperties.GetIsInDesignMode(Application.Current.RootVisual); }
Thanks for the tip Tom!