理论上,mvvmlight 中的消息传递应该是一劳永逸的......发送者不关心谁收到消息,接收者也不关心谁发送消息,只要它正在侦听的正确类型。
我通过多次尝试和错误发现,制作自己的消息比使用 mvvm-light 提供的默认消息要容易得多,它们是一个很好的起点,但有时你会发现自己在跳槽..
public class ExceptionMessage : GalaSoft.MvvmLight.Messaging.GenericMessage<System.Exception>
{
public ExceptionMessage(System.Exception content) : base(content) { }
public ExceptionMessage(object sender, System.Exception content) : base(sender, content) { }
public ExceptionMessage(object sender, object target, System.Exception content) : base(sender, target, content) { }
}
收货人代码:
Messenger.Default.Register<Core.Messaging.ExceptionMessage>(this, ex => ShowExceptionMessage(ex));
发件人代码:
public void LogException(Exception content)
{
_messenger.Send<Core.Messaging.ExceptionMessage>(new ExceptionMessage(content));
//GetBw().RunWorkerAsync(content);
WriteToDatabaseLog(content);
}
是的,这确实违反了我第一句话中的建议,但理论上我可以拥有多个 vm 或查看监听异常消息。
也许另一个例子可以帮助你...我讨厌整个 foo 的事情...它总是让我感到困惑...
这是我的核心模块:
public class SaveNotification<T> : GalaSoft.MvvmLight.Messaging.NotificationMessage<T> where T : GalaSoft.MvvmLight.ViewModelBase
{
public SaveNotification(T content, string notification) : base(content, notification) { }
public SaveNotification(object sender, T content, string notification) : base(sender, content, notification) { }
public SaveNotification(object sender, object target, T content, string notification) : base(sender, target, content, notification) { }
}
这是我在我的虚拟机中使用它的方式:
public void OnSubmitChanges(SubmitOperation so)
{
if (so.HasError)
{
Infrastructure.GetService<IExceptionLoggingInterface>().LogException(this, so.Error);
}
else
{
//Save Responses
_messenger.Send<Messages.NavigationRequest<SubClasses.URI.PageURI>>(GetNavRequest_HOME());
ClearQuestionaire(true);
_messenger.Send<WavelengthIS.Core.Messaging.SaveNotification<QuestionairreViewModel>>(GetSuccessfulSaveNotification());
}
Wait.End();
}
private WavelengthIS.Core.Messaging.SaveNotification<QuestionairreViewModel> GetSuccessfulSaveNotification()
{
return new WavelengthIS.Core.Messaging.SaveNotification<QuestionairreViewModel>(this, "Save Successfull");
}