views:

90

answers:

1

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.

A: 

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

Andréas Saudemont
Andreas: You are right of course. However, the point of using System.Threading.Timer in this particular example was to explicitly cause a background thread to be used (this app is a demonstration of how to do cross-threaded messaging in a WP7 app).
cek
Then DispatcherTimer would indeed defeat the purpose. :)
Andréas Saudemont
Just a thought: does the PowerState property raise PropertyChanged when its value changes?
Andréas Saudemont
yes, it does. Why?
cek
Yes it does (in both the Model and the ViewModel). See this question where more details of why I wrote this sample are exposed: http://stackoverflow.com/questions/3655422/a-super-simple-mvvm-light-wp7-sample
cek
I was wondering whether the PropertyChanged event could be raised outside the UI thread (which might give some insight on the crash you experience), but looking at your code that's not the case.
Andréas Saudemont