2011-08-01 31 views

回答

3

你可以這樣做:

<Menu Height="23" HorizontalAlignment="Left" Name="menu1" VerticalAlignment="Top" Width="289" > 
    <MenuItem Header="File"> 
     <MenuItem Header="Save" Command="Save"/> 
    </MenuItem> 
</Menu> 

我敢肯定,這將調用默認的保存方法,但是如果你要定義一個自定義的保存方法,你可以這樣做:

<Menu Height="23" HorizontalAlignment="Left" Name="menu1" VerticalAlignment="Top" Width="289" > 
    <MenuItem Header="File"> 
     <MenuItem Header="Save" Command="{Binding Path="CustomSaveCommand"}"/> 
    </MenuItem> 
</Menu> 

確保你添加一個datacontext參考到你的視圖模型像這樣

<Window.DataContext> 
    <my:MainWindowViewModel/> 
</Window.DataContext> 
+0

是的,但這會調用主窗口的CustomSaveCommand。我想調用CustomerViewModel的CustomSaveCommand。 – Pak

+0

然後簡單地將您的DataContext更改爲任何您希望的內容。這只是一個例子,並不一定適用於您的情況。 – Paul

0

感謝您的回覆,保羅。這是我最終做的。 正如我上面提到的,我使用Josh Smith的設計,我想從MainWindowViewModel調用Save()方法(命令)CustomerViewModel對象。 因此,從主窗口中,我將一個單擊事件附加到我的工具欄按鈕中。

<Button Name="btnSaveAllWorkspaces" ToolTip="Save All Open Workspaces" Content="Save All" Click="OnSaveAllWorkspacesClicked"/>   

然後在後面的代碼,

private void OnSaveAllWorkspacesClicked(object sender, RoutedEventArgs e) 
    { 
     if (MainVM != null) 
     { 
      if (MainVM.Workspaces != null && MainVM.Workspaces.Count > 0) 
      { 
       foreach (WorkspaceViewModel wkVM in MainVM.Workspaces) 
       { 
        CustomerViewModel vm = wkVM as CustomerViewModel; 
        if (vm != null) 
         vm.Save(); 
       } 
      } 
     } 
    } 

起初,我只是想只保存當前激活的工作空間,但轉念一想,因爲它是對所有的工作區的頂部全球按鈕,它保存所有打開的工作區是有意義的,因此可以使用foreach循環。

如果有更好的方法來通過XAML來實現這一點,請分享一下嗎?

感謝

0

我知道無論我此前做的是一個解決辦法,這是骯髒的。隨着我對MVVM的更多瞭解,我不斷重新考慮代碼。這就是我所做的。

在MainWindowViewModel上添加了SaveCommand的ICommand Proerty,並將其綁定到主窗口上的工具按鈕。它只是將調用委託給當前活動的WorksSpaceViewModel的SaveCommand。

public override ICommand SaveCommand 
    { 
     get 
     { 
      return _currentWorkspace != null ? _currentWorkspace.SaveCommand : new RelayCommand (null, param => false); 
     } 
    } 

,並在原來的代碼,它跟蹤當前工作區,確保我的更改通知

public ObservableCollection<WorkspaceViewModel> Workspaces 
    { 
     get 
     { 
      if (_workspaces == null) 
      { 
       _workspaces = new ObservableCollection<WorkspaceViewModel>(); 
       _workspaces.CollectionChanged += OnWorkspacesChanged; 
       CollectionViewSource.GetDefaultView(_workspaces).CurrentChanged += new EventHandler(MainWindowViewModel_CurrentChanged); 
      } 
      return _workspaces; 
     } 
    } 

    private void MainWindowViewModel_CurrentChanged(object sender, EventArgs e) 
    { 
     CurrentWorkspace = CollectionViewSource.GetDefaultView(_workspaces).CurrentItem as WorkspaceViewModel; 
     OnPropertyChanged("SaveCommand"); 
    } 

    public WorkspaceViewModel CurrentWorkspace 
    { 
     get { return _currentWorkspace; } 
     set 
     { 
      _currentWorkspace = value; 
      OnPropertyChanged("CurrentWorkspace"); 
     } 
    } 

就是這樣,WPF把剩下的事情的子系統(即根據驗證啓用,禁用按鈕)!

再一次,感謝您的提示保羅。

相關問題