适用于 Windows Phone 7 和 Windows Phone 7 的 VS2010与 Mvvm-Light 混合崩溃

发布于 2024-09-18 08:43:19 字数 1075 浏览 2 评论 0原文

这实际上并不是一个问题,而是一个断言。发布此内容以便其他人可以避免此问题。

如果您使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

看轻我的陪伴 2024-09-25 08:43:19

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文