2012-02-02 65 views
1

我正在使用MVVM轻型工具包的Messenger类来传达WP7应用程序的不同部分。使用MVVM Light在WP7项目中引发的UnauthorizedAccessException(无效的跨线程访问)

我想从一个类的应用程序接收消息时使视图转到不同的状态。在视图的代码隐藏我注册的消息:

Messenger.Default.Register<PageActionMessage> 
(
    this, 
    (action) => GoToPage(action) 
); 

,并调用时,收到以下方法:

private object GoToPage(PageActionMessage action) 
{ 
    if (action.action == PageAction.TwitterAuthFinished) 
    { 
     if (IsoStoreHelper.CheckIfAuthorized()) 
     { 
      VisualStateManager.GoToState(this, "TwitterSendPage", true); // The exception is thrown here 
     } 
    } 
} 

在我的其他类中,广播这条消息是这样的:

var PageMsg = new PageActionMessage() 
{ 
    action = PageAction.TwitterAuthFinished 
}; 
Messenger.Default.Send<PageActionMessage>(PageMsg); 

此消息被视图正确接收,但在调用VisualStateManager的GoToState方法时,会引发一个UnauthorizedAccessException(无效的跨线程访问)降低轨迹:

System.UnauthorizedAccessException was unhandled 
    Message=Invalid cross-thread access. 
StackTrace: 
    at MS.Internal.XcpImports.CheckThread() 
    at System.Windows.DependencyObject.GetValueInternal(DependencyProperty dp) 
    at System.Windows.FrameworkElement.GetValueInternal(DependencyProperty dp) 
    at System.Windows.DependencyObject.GetValue(DependencyProperty dp) 
    at System.Windows.Controls.Panel.get_Children() 
    at MS.Internal.XcpImports.CheckThread() 
    at MS.Internal.XcpImports.Control_GetImplementationRoot(Control control) 
    at System.Windows.Controls.Control.get_ImplementationRoot() 
    at System.Windows.VisualStateManager.GoToState(Control control, String stateName, Boolean useTransitions) 
    at KidsBook.MainPage.GoToPage(PageActionMessage action) 
    at KidsBook.MainPage.<.ctor>b__0(PageActionMessage action) 
    at GalaSoft.MvvmLight.Helpers.WeakAction`1.Execute(PageActionMessage parameter) 
    at GalaSoft.MvvmLight.Helpers.WeakAction`1.ExecuteWithObject(Object parameter) 
    at GalaSoft.MvvmLight.Messaging.Messenger.SendToList[TMessage](PageActionMessage message, IEnumerable`1 list, Type messageTargetType, Object token) 
    at GalaSoft.MvvmLight.Messaging.Messenger.SendToTargetOrType[TMessage](PageActionMessage message, Type messageTargetType, Object token) 
    at GalaSoft.MvvmLight.Messaging.Messenger.Send[TMessage](PageActionMessage message) 
    at KidsBook.Twitter.OAuthClient.GetResponse(IAsyncResult result) 
    at System.Net.Browser.ClientHttpWebRequest.<>c__DisplayClassa.<InvokeGetResponseCallback>b__8(Object state2) 
    at System.Threading.ThreadPool.WorkItem.WaitCallback_Context(Object state) 
    at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) 
    at System.Threading.ThreadPool.WorkItem.doWork(Object o) 
    at System.Threading.Timer.ring() 

这是由于什么造成的?提前致谢!

+0

你的代码试图从不同的线程在UI线程访问和设置的VisualState,尝试在VisualStateManager使用调度呼叫。 – BigL 2012-02-02 11:38:24

回答

4

使用MVVVMLight,您可以使用DispatcherHelper确保代码在UI线程(您的问题)上运行。
例如

DispatcherHelper.CheckBeginInvokeOnUI(YOUR-ACTION); 
相关问题