我在我的ViewModel中的NotifyPropertyChanged方法中使用来自MVVM灯的DispatcherHelper来封送对UI线程的调用。 在我的Application_Launching中,我像这样初始化Dispatcher:
DispatcherHelper.Initialize();
我也将其添加到Application_Activated
当应用程序墓碑我将我的VM保存到“状态”字典时。当应用程序从逻辑删除状态重新激活时,平台似乎首先在触发Application_Activated之前执行ViewModel的反序列化。作为反序列化的一部分,设置ViewModel的属性,然后在视图模型中调用NotifyProperyChanged方法。这反过来调用DispatcherHelper,但由于尚未调用“Initialize”方法,MVVM Light会抛出“null引用异常”
所以问题是我在哪里调用DispatcherHelper.Initialize()。
编辑1 我注意到如果我将我的VM保存在“Application_Deactivated”处理程序
中PhoneApplicationService.Current.State[viewModelKey] = ViewModel;
然后返回应用程序重新激活它,我在“调用堆栈视图”中看到以下调用,并启用“显示外部代码”“
Microsoft.Phone.dll!Microsoft.Phone.Shell.StreamPersister.Deserialize(byte[] blob, System.Collections.Generic.IEnumerable<System.Type> knownTypes, ref System.Collections.Generic.IDictionary<string,object> dictionary) + 0x20 bytes
Microsoft.Phone.dll!Microsoft.Phone.Shell.StreamPersister.Load(Microsoft.Phone.Shell.Interop.ShellPageManager shellPageManager, string key, System.Collections.Generic.IEnumerable<System.Type> knownTypes, ref System.Collections.Generic.IDictionary<string,object> dictionary) + 0x28 bytes
Microsoft.Phone.dll!Microsoft.Phone.Shell.PhoneApplicationService.FireActivated(bool isExecutionContextPreserved) + 0x30 bytes
Microsoft.Phone.Interop.dll!Microsoft.Phone.Execution.NativeEmInterop.FireOnResume(bool isExecutionContextPreserved) + 0xc bytes
如果我不将我的ViewModel添加到状态字典
,则不会出现这些调用编辑2: 如果我将调用替换为DispatchHelper并将其替换为标准的Dispatcher.BeginInvoke,则问题就会消失。
CHANGE Deployment.Current.Dispatcher.BeginInvoke ( ()=&gt; { //做任何事 } )
对此 DispatcherHelper.CheckBeginInvokeOnUI ( ()=&gt; { //做任何事 } )