2013-10-10 71 views
2

我想從我的孩子ViewModel事件回傳給父母。子viewmodel的視圖是一個單獨的窗口,我相信我不能傳遞構造函數參數。該視圖上的按鈕需要在父視圖模型上觸發一個方法。ViewModel與事件之間的通信

子視圖模型:

public ConnectViewModel(ConnectEvents connectEvents) 
{ 
    ConnectEvents = connectEvents; 
} 

父視圖模型

public MainWindowViewModel() 
{ 
    ConnectEvents connectEvents = new ConnectEvents(); 
    ConnectViewModel = new ConnectViewModel(connectEvents); 
    connectEvents.ThrowEvent += ConnectToServer; 
} 

我如何在這兩者之間進行溝通?有一個更好的系統,或者我如何讓父母訂閱孩子?

+0

如果你真的想實現MVVM,你應該看看一個命令模式。 – Tico

+0

是否可以將命令傳遞給另一個視圖模型?他們有不同的dataContexts。 – user547794

+0

這就是它的作用,看看定義:http://en.wikipedia.org/wiki/Command_pattern – Tico

回答

2

溝通 '事件' 通過事件

在你ConnectViewModel ...

public ConnectViewModel(ConnectEvents connectEvents) 
{ 
    public event EventHandler<EventArgs> SomethingHappenedEvent; 

    ... 

    private void DoSomething() 
    { 
      if (SomethingHappenedEvent != null) 
      { 
       SomethingHappenedEvent(this, newEventArgs()); 
      } 
    } 

    RelayComand _somethingCommand; 
    public ICommand SomethingHappenedCommand 
    { 
      get 
      { 
       if (_someethingCommand == null) 
        _somethingCommand = new RelayCommand(DoSomething) 
      } 
    } 
} 

,並在您MainWindowViewModel

public MainWindowViewModel() 
{ 
    ConnectEvents connectEvents = new ConnectEvents(); 
    ConnectViewModel = new ConnectViewModel(connectEvents); 
    ConnectViewModel.SomethingHappenedEvent += HandleSomethingHappened; 
    connectEvents.ThrowEvent += ConnectToServer; 
} 
private void HandleSomethingHappened(object sender, EventArgs e) 
{ 
    // Now your mainviewmodel knows that something happened 
} 
2

你可以使自己的EventAggregator

public static class DumbAggregator 
{ 
    public static void BroadCast(string message) 
    { 
    if (OnMessageTransmitted != null) 
     OnMessageTransmitted(message); 
    } 

public static Action<string> OnMessageTransmitted; 
} 

用法:

public class MySender 
    { 
    public void SendMessage() 
    { 
     DumbAggregator.BroadCast("Hello There!"); 
    } 
    } 

public class MySubscriber 
{ 
    public MySubscriber() 
    { 
    DumbAggregator.OnMessageTransmitted += OnMessageReceived; 
    } 

private void OnMessageReceived(string message) 
{ 
    MessageBox.Show("I Received a Message! - " + message); 
} 
} 

,並用這個你可以與你的視圖模型