2012-03-07 27 views
1

是否有可能使用Prism從WPF應用程序中的不同ViewModels執行某種命令?從不同的ViewModel執行相同的Prism命令

讓我解釋一下我的意思。

我有MainMenuViewModel類:

public class MainMenuViewModel 
{ 
    private ICommand _aboutCommand; 
    public ICommand AboutCommand 
    { 
     get 
     { 
      if (_aboutCommand == null) 
      { 
       _aboutCommand = new DelegateCommand(() => 
        { MessageBox.Show("About menu item clicked!"); }); 
      } 

      return _aboutCommand; 
     } 
    } 
} 

也有此模型的視圖:

<Menu IsMainMenu="True"> 
    <MenuItem Header="Nápověda"> 
     <MenuItem Header="O Aplikaci" x:Name="About" 
        Command="{Binding AboutCommand}" /> 
    </MenuItem> 
</Menu> 

有一個在應用程序的另一個模塊,它應該具有相同的行爲執行命令(甚至可能更好 - 相同的命令):

public class MunisatorViewModel 
{ 
    private ICommand _aboutCommandInAnotherModule; 

    public ICommand AboutCommandInAnotherModule 
    { 
     get 
     { 
      if (_aboutCommandInAnotherModule== null) 
      { 
       _aboutCommandInAnotherModule= new DelegateCommand(() => 
        { MessageBox.Show("About menu item clicked!"); }); 
      } 

      return _aboutCommandInAnotherModule; 
     } 
    } 
} 

此模塊具有查看:

<StackPanel Background="White" HorizontalAlignment="Center" VerticalAlignment="Top"> 
    <Button cmd:Click.Command="{Binding AboutCommandInAnotherModule}">About</Button> 
</StackPanel> 

是否有可能避免重複的代碼?

P.S.我明白,我可以爲這兩個ViewModel創建基類,並在那裏描述這個Commands,但問題是,一些ViewModel已經有了不同的基類。

回答

2

使用EventAggregator來引發這樣的事件。這使您可以在UI的不同區域之間進行鬆散耦合的通信。

通過實現CompositeEvent對象傳遞數據的發佈/訂閱概念運行良好。

或者,你可以讓你的命令是靜態的,並從不同的地方訪問它,但這看起來並不那麼好。

Prism documentation詳細介紹了您的選項。

希望有所幫助。

+0

我知道EventAggregator,但在這種情況下無法避免重複的代碼。 – msi 2012-03-07 23:15:42

+0

是的,它確實... MainMenuViewModel將實現顯示關於菜單的代碼。它還將訂閱名爲「AboutCommandFired」的事件,MunisatorViewModel將發佈該事件。在您的MainMenuViewModel中,您可能還需要將實現移出匿名方法,以便可以從DelegateCommand和事件聚合器中調用它。 – lecrank 2012-03-07 23:48:13

+0

但在這種情況下,我仍然應該複製創建命令的代碼,並將不同的命令分配給視圖。我的問題是,如果可以對不同的視圖使用SAME Command實現。 – msi 2012-03-08 09:22:39

0

也許你可以重構你的AboutCommand到一個單獨的類/對象,這則可能被注入到雙方的ViewModels(構造函數,二傳...)。通過這種方式,每個視圖模型只會提供對命令對象的引用,並且會從您的主視圖模型中將「AboutCommand」邏輯「外包」的代價重複。

另一個更靜態的方式可能是使用含有CompositeCommands,例如您的AboutCommand命令代理。任何地方你都可以註冊(或多個)關於about命令的實現。

希望這會有所幫助。

相關問題