2011-05-26 159 views
1
public class Foo<T> where T: Entity 
{} 

public class Foo1 
: Foo<Telephone> 
{ 
} 

public class Foo2 
: Foo<Home> 
{ 
} 

如何將Foo1發送到Foo2?我意識到消息是鍵入的,因此消息是相同類型的接收 - 但我需要派生類之間的消息...發送通用消息

一個例子將非常感激。

回答

1

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"); 
     } 
+0

標誌着我這是一個答案,因爲我也希望看到的方式來解決我的問題,我從來沒有見過GenericMessage的例子。不過,我認爲這不會解決我的問題。 在我的例子中,Foo1和Foo2實際上是兩種不同的類型 - 因爲類型是在編譯時(不是運行時)定義的。我知道這一點,但當我被困在這個問題上的時候沒有想到它(我猜在鍵盤上有太多的時間了!) 我如何通過從基類中提取的接口解決我的問題。使用界面創建的消息 - 爲所有人提供通用界面。 – codeputer 2011-05-27 16:03:50

2

另一種方法是創建自己的類,它包含要傳遞(Foo1或者乾脆object)的有效載荷。然後在Foo2中,註冊以接收剛創建的類的類型的消息。

這個鏈接解釋瞭如何用一個很容易理解的例子。

MVVM Light Toolkit Soup To Nuts 3 - Jesse Liberty