How do I stop my ViewModel code from running in the designer?
Just to add to these suggestions, you probably want to optimize for production deployment.
If you need to check the design mode in the ViewModel, you should only do so when in DEBUG
mode, otherwise the released version will always have to perform unnecessary checks.
When developing, if in design mode you can exit the method (or even stub out some fake data).
Put this code as the first line of your constructor (or whatever code is being called):
C#:
#if DEBUG if (DesignerProperties.GetIsInDesignMode(new DependencyObject())) return;#endif
VB:
#If DEBUG Then If DesignerProperties.GetIsInDesignMode(New DependencyObject()) Then Return#End If
I thought I'll add to this as I've just looked up something I spotted in VS2015 and it provides an alternative solution. In the designer there is a button to "Disable project code".
I'm making the assumption that your ViewModel
is being instantiated and doing stuff from your code behind. I know it breaks pure MVVM, but I've seen plenty of people do stuff like DataContext = new MyViewModel();
within the constructor in the code behind.
Toggling this button should solve that issue and helps to keep your code cleaner. Checkout MSDN for more information.
Here's the image from the MSDN documentation so you know what it looks like. I'm sure the link will break eventually, anyway.
I spotted this in VS2015, but not sure which edition this feature was added.
As a side note, it also doubles up as a nice way to reload the designer. Albeit a slow one when I tried. Your milage may vary.