希望我能在这里给出一个清晰的问题描述,我在我当前的 WPF 应用程序分配中实现了 MVVM。
我所做的是,我创建了一个继承 Window 的基类,然后每个其他窗口都继承这个类。
public class ApplicationScreenBase : Window
{
public ApplicationScreenBase()
{
AppMessenger.Register(this, OnMessageToApp);
this.Unloaded += ApplicationScreenBase_Unloaded;
}
private void ApplicationScreenBase_Unloaded(object sender, RoutedEventArgs e)
{
AppMessenger.Unregister(this, OnMessageToApp);
}
private void OnMessageToApp(AppMessage message)
{
switch (message.MessageType)
{
case AppMessageType.Navigate:
{
var CurrentWindow = Activator.CreateInstance(Locator.NavigationPageLocator.LocateNavigateTypeByEnum((NavigationScreens)message.MessageData)) as Window;
CurrentWindow.Show();
this.Close();
break;
}
case AppMessageType.NewWindow:
{
var CurrentWindow = Activator.CreateInstance(Locator.NavigationPageLocator.LocateNavigateTypeByEnum((NavigationScreens)message.MessageData)) as Window;
CurrentWindow.Show();
break;
}
case AppMessageType.MessageBox:
{
MessageBox.Show(message.MessageData.ToString());
break;
}
case AppMessageType.Close:
{
this.Close();
break;
}
default:
break;
}
}
}
这是我的导航类,它返回我要打开的窗口类型。
public static class NavigationPageLocator
{
public static Type LocateNavigateTypeByEnum(NavigationScreens navigationPage)
{
switch (navigationPage)
{
case NavigationScreens.LoginOnline:
return typeof(LoginOnline);
case NavigationScreens.MainWindow:
return typeof(MainWindow);
case NavigationScreens.Home:
return typeof(Home);
}
return default(Type);
}
}
这就是我使用 AppMessenger 的方式
public enum AppMessageType
{
Navigate,
NewWindow,
Close,
MessageBox
}
public class AppMessage
{
public AppMessageType MessageType { get; set; }
public object MessageData { get; set; }
}
public class AppMessenger
{
public static void Register(object recipient, Action<AppMessage> action)
{
Messenger.Default.Register<AppMessage>(recipient, action);
}
public static void Unregister(object recipient, Action<AppMessage> action)
{
Messenger.Default.Unregister<AppMessage>(recipient, action);
}
public static void Send(AppMessage message)
{
Messenger.Default.Send<AppMessage>(message);
}
这就是我控制 ViewModel 的流程-
AppMessenger.Send(new AppMessage() { MessageType = AppMessageType.Navigate, MessageData = NavigationScreens.Home });
**现在问题是我成功注册到窗口,我发现 AppMessenger 的单个实例注册到每个窗口,但是当我通知信使调用某个事件时,它会触发两次。例如
AppMessenger.Send(new AppMessage() { MessageType = AppMessageType.MessageBox, MessageData = "Authentication failed." });
这将显示两次 MessageBox。请为此提出任何解决方案。
不知道怎么打了两次。我该如何防止这种情况。有什么帮助吗?谢谢。**