适用于 Windows Phone 7 和 Windows Phone 7 的 VS2010与 Mvvm-Light 混合崩溃
这实际上并不是一个问题,而是一个断言。发布此内容以便其他人可以避免此问题。
如果您使用 Mvvm-Light(也可能是其他 Mvvm 框架)并且 ViewModel 中的代码在 UI 线程以外的线程上运行,则在尝试在设计模式下查看/编辑 XAML 时,VS2010 和 Exression Blend 可能会崩溃。
例如,我有一个 CheckBox 绑定到一个由在后台线程上更新的对象实现的属性:
<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" />
在 Switch 类(派生自 ViewModelBase)类中,我创建一个计时器,每 5 秒更改一次 PowerState 属性(从 true 到错误并再次返回)。
因为 VS2010/Blend 设计人员在设计时运行我的代码,所以该代码被调用并且计时器被触发。两个应用程序都在我的计时器回调函数中崩溃了。
解决方法很简单:
记住将您不想在设计时运行的任何代码包装在 IsInDesignMode
条件中。像这样。
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 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您还可以使用 DispatcherTimer< /a> 而不是计时器。您将失去一点准确性,但另一方面,回调将在 UI 线程上调用,这可能会防止崩溃(或不会)。
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).