我使用的是Prism,我有一个状态模块,具有以下ViewModel:
public class StatusViewModel : WorkSpaceViewModel, IStatusQueryViewModel
{
private bool _isActive;
private StatusContext _context;
public StatusViewModel(IEventAggregator eventAggregator)
{
eventAggregator.GetEvent<StatusEvent>()
.Subscribe(x => UpdateStatus(x), ThreadOption.UIThread, true);
IsActive = false;
}
public bool IsActive
{
get { return _isActive; }
set { SetProperty(ref _isActive, value); }
}
public StatusContext Context
{
get { return _context; }
set { SetProperty(ref _context, value); }
}
private void UpdateStatus(StatusContext context)
{
if (context != null)
{
Context = context;
IsActive = true;
if (Context.Callback != null)
{
Timer t = new Timer(x =>
{
Context.Callback.Invoke();
IsActive = false;
}, null, 3000, 0);
}
}
}
}
所以,当我触发状态时,比如:
_statusQuery.SetStatus(new StatusContext(string.Format("Cargando datos del servidor {0}", server.NombreInstancia),StatusType.Informative,
() =>
{
var targetUri = new Uri("SqlMasterView", UriKind.Relative);
var navParameters = new NavigationParameters();
navParameters.Add("selectedServer", server);
_regionManager.RequestNavigate(RegionNames.ServerInfoBarRegion, targetUri, navParameters);
}));
代码在StatusViewModel中的callback.invoke之后运行,但在调试器中没有发生任何事情,也没有弹出视图,它显示:
A first chance exception of type 'System.InvalidOperationException' occurred in PresentationCore.dll
A first chance exception of type 'System.InvalidOperationException' occurred in Microsoft.Practices.Unity.dll
A first chance exception of type 'Microsoft.Practices.Unity.ResolutionFailedException' occurred in Microsoft.Practices.Unity.dll
A first chance exception of type 'Microsoft.Practices.ServiceLocation.ActivationException' occurred in Microsoft.Practices.ServiceLocation.dll
A first chance exception of type 'System.InvalidOperationException' occurred in Prism.Wpf.dll
顺便说一句,不知道这是否重要,但statusQuery被封装在另一个回调中:
_dialogQuery.Publish(
new DialogContext(DialogType.Prompt,
String.Format("Desea cargar los datos del servidor {0}?", server.NombreInstancia), null, x =>
{
bool b = x == DialogResult.Ok;
if (b)
{
_statusQuery.SetStatus(new StatusContext(string.Format("Cargando datos del servidor {0}", server.NombreInstancia),StatusType.Informative,
() =>
{
var targetUri = new Uri("SqlMasterView", UriKind.Relative);
var navParameters = new NavigationParameters();
navParameters.Add("selectedServer", server);
_regionManager.RequestNavigate(RegionNames.ServerInfoBarRegion, targetUri, navParameters);
}));
}
}));
也许这与线程有关?谢谢
编辑:在使用状态查询之前,代码运行良好
编辑2:我尝试了System.Timers.Timer和First Chance异常无论如何都会抛出
好吧,如果有人带着同样的问题来到这里,Dispatcher会解决它:
Application.Current.Dispatcher.BeginInvoke((System.Windows.Threading.DispatcherPriority.Normal),
(Action)(() =>
{
Context.Callback.Invoke();
IsActive = false;
Dispose();
}
));