4
votes

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.

1
Just to be clear: This is not directly related to MVVM Light, but rather to the fact that VS10 designer and Blend run the code when the application is loaded. Because MVVM Light enables blendability (by the way that things are wired up), this can occur. In which case, it may be necessary to attach a debugger to Expression Blend (or even the VS10 designer) to find the cause of the issue.LBugnion

1 Answers

0
votes

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).