Search code examples
silverlightvisual-studio-2010expression-blendwindows-phone-7mvvm-light

VS2010 for Windows Phone 7 & Blend crash with Mvvm-Light


This is not really a question, but an assertion. Posting this so that others can avoid this problem.

If you use Mvvm-Light (and maybe other Mvvm frameworks) and have code in your ViewModel that runs on a thread other than the UI thread, VS2010 and Exression Blend will likely crash when trying to view/edit your XAML in design mode.

For example I have a CheckBox bound to a property that is implemented by an object that gets updated on a background thread:

<CheckBox Content="Switch 1" 
          IsChecked="{Binding Switch1.PowerState, Mode=TwoWay}"
          Height="72" HorizontalAlignment="Left" Margin="24,233,0,0" 
          Name="checkBox1" VerticalAlignment="Top" Width="428" />

In the Switch class (derived from ViewModelBase) class I create a timer that changes the PowerState property every 5 seconds (from true to false and back again).

Because the VS2010/Blend designers run my code at design time, this code was being called and the timer was firing. Both apps crashed in my timer callback function.

The fix is easy:

Remember to wrap any code that you DON'T WANT RUN at design time in a IsInDesignMode conditional. Like this.

    public OnOffSwitchClass()
    {
        if (IsInDesignMode)
        {
            // Code runs in Blend --> create design time data.
        }
        else
        {
            _timer = new System.Threading.Timer(TimerCB, this, TIMER_INTERVAL, TIMER_INTERVAL);
        }
    }

This fixed it for me. Hope it helps you.


Solution

  • You could also use DispatcherTimer instead of Timer. You will lose a bit of accuracy but on the other hand the callback will be invoked on the UI thread, which might prevent the crashes (or not).