发送通用消息
问题描述:
public class Foo<T> where T: Entity
{}
public class Foo1
: Foo<Telephone>
{
}
public class Foo2
: Foo<Home>
{
}
如何将Foo1发送到Foo2?我意识到消息是键入的,因此消息是相同类型的接收 - 但我需要派生类之间的消息...发送通用消息
一个例子将非常感激。
答
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);
}
和肯定这是否打破送我的第一建议但理论上我可以有几个vms或视图监听异常消息。
也许另一个例子来帮助你......我恨整个富东西...它总是让我困惑...
这是我的核心模块:
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");
}
答
另一种方法是创建自己的类,它包含要传递(Foo1
或者干脆object
)的有效载荷。然后在Foo2
中,注册以接收刚创建的类的类型的消息。
这个链接解释了如何用一个很容易理解的例子。
标志着我这是一个答案,因为我也希望看到的方式来解决我的问题,我从来没有见过GenericMessage的例子。不过,我认为这不会解决我的问题。 在我的例子中,Foo1和Foo2实际上是两种不同的类型 - 因为类型是在编译时(不是运行时)定义的。我知道这一点,但当我被困在这个问题上的时候没有想到它(我猜在键盘上有太多的时间了!) 我如何通过从基类中提取的接口解决我的问题。使用界面创建的消息 - 为所有人提供通用界面。 – codeputer 2011-05-27 16:03:50