簡體   English   中英

從不同窗口的視圖模型調用窗口中的函數

[英]Calling a function in a Window from a different Window's View Model

所以,我目前有 2 個窗口(MainWindow、SubWindow)和一個視圖模型。 MainWindow 主要只是一個使用hardcodet.wpf.taskbarnotification.taskbaricon的任務欄圖標。 單擊此任務欄圖標上下文菜單中的按鈕會打開子窗口。

SubWindow 的 DataContext 設置為視圖模型。 SubWindow 允許用戶輸入一堆數據並單擊“上傳”按鈕,這會將所有這些數據發送到我之前編寫的服務。 此服務將對數據執行許多操作並返回單個字符串。 我目前的目標是獲取這個返回的字符串並在 MainWindow 中使用它,但這就是我的問題所在。

對服務的調用是在 ViewModel 中完成的,我不確定如何將響應返回給 MainWindow。 我最初的想法是只引用其他對象中的每個對象(即引用 SubWindow 中的 MainWindow 和 ViewModel 中的 SubWindow),但是我寧願避免這樣做。 我也考慮過事件,但是我一直無法弄清楚如何讓事件在 ViewModel 和 MainWindow 之間工作。

任何關於我應該如何舉辦活動或我應該嘗試做的其他事情的任何幫助/建議將不勝感激。 如果需要更多信息,請告訴我。

使用 MVVM Light Messenger

 > http://dotnetpattern.com/mvvm-light-messenger
public class ViewModelA : ViewModelBase
{
    public void SearchCommandMethod()
    {
        MessengerInstance.Send<NotificationMessage>(new NotificationMessage("notification message"));
    }
}

Jesse Liberty of Microsoft has a great concrete walk through on how to make use of the messaging within MVVM Light. The premise is to create a class which will act as your message type, subscribe, then publish.

public class GoToPageMessage
{
   public string PageName { get; set; }
}
This will essentially send the message based on the above type/class...

    private object GoToPage2()
    {
       var msg = new GoToPageMessage() { PageName = "Page2" };
       Messenger.Default.Send<GoToPageMessage>( msg );
       return null;
    }

Now you can register for the given message type, which is the same class defined above and provide the method which will get called when the message is received, in this instance ReceiveMessage.

    Messenger.Default.Register<GoToPageMessage>
    ( 
         this, 
         ( action ) => ReceiveMessage( action ) 
    );

    private object ReceiveMessage( GoToPageMessage action )
    {
       StringBuilder sb = new StringBuilder( "/Views/" );
       sb.Append( action.PageName );
       sb.Append( ".xaml" );
       NavigationService.Navigate( 
          new System.Uri( sb.ToString(), 
                System.UriKind.Relative ) );
       return null;
    }

您是否嘗試過將委托(函數回調)從主窗口視圖模型傳遞到子窗口? 所以子窗口可以調用這個方法把結果傳回主窗體。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM