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

This is not a question, but a statement. By doing this so that others can avoid this problem.

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

For example, I have a CheckBox binding to a property that is implemented by an object that is updated in the 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), I create a timer that changes the PowerState property every 5 seconds (from true to false and vice versa).

Since the designers of VS2010 / Blend run my code during development, this code is called and the timer starts. Both applications crashed in my timer callback function.

Easy fix:

Do not forget to wrap any code that you DO NOT WANT during development in the conditions of IsInDesignMode . 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 this helps you.

+4
source share
1 answer

You can also use DispatcherTimer instead of a timer. You will lose a bit of precision, but on the other hand, the callback will be called in the user interface thread, which can prevent crashes (or not).

0
source

All Articles