2013-06-02 19 views
1

在我的項目中,我有一個TitleViewGameView。當程序啓動時,顯示TitleView。用戶單擊一個按鈕並顯示GameView。我使用MVVM光,其中包括MainViewModel具有命令,切換到所需的觀點:MVVM - 在XAML中從不同類訪問命令

MainViewModel.cs

GameViewCommand = new RelayCommand(() => ExecuteGameViewCommand()); 

private void ExecuteGameViewCommand() 
{ 
    CurrentViewModel = MainViewModel._gameViewModel; 
} 

在TitleView.xaml,我需要訪問這個命令,我不知道怎麼辦。當談到XAML時,我非常喜歡新手。

TitleView.xaml

<UserControl x:Class="AoW.Views.TitleView" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
     xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
     xmlns:vm="clr-namespace:AoW.ViewModels" 
     mc:Ignorable="d" 
     d:DesignWidth="1020" 
     d:DesignHeight="740" 
     Width="1020" 
     Height="740"> 

    <Button Content="New Game" 
      //This needs to bind to GameViewCommand in MainViewModel.cs 
      Command="{Binding GameViewCommand}" 
      Grid.Column="1" 
      Grid.Row="1" 
      HorizontalAlignment="Center" 
      VerticalAlignment="Center" /> 

如果我把以下行TitleView.xaml ...

DataContext="{Binding Main, Source={StaticResource Locator}}" 

...我可以訪問GameViewCommand,但我不能訪問任何地方的命令。

如何在保持對本地命令的控制權的同時訪問GameViewCommand?

如果提供額外的代碼會有幫助,請讓我知道。

+0

您已將Button的command屬性綁定到您的GameViewCommand。 Xaml中還有哪些地方需要訪問? –

+0

'GameViewCommand'在'MainViewModel'中。我想找到一種方法將該命令綁定到'TitleView'中的按鈕。這可能嗎? –

+0

您是否考慮將它重構爲BaseViewModel作爲靜態成員並在那裏指定處理邏輯? –

回答

0

我修復了這個問題。所有我必須是這樣的:

<Button Content="New Game" 
      Command="{Binding GameViewCommand}" 
      DataContext="{Binding Main, Source={StaticResource Locator}}" 
      Grid.Column="1" 
      Grid.Row="1" 
      HorizontalAlignment="Center" 
      VerticalAlignment="Center" /> 

<Button Content="Say Hello" 
      Command="{Binding SayHelloCommand}"    
      Grid.Column="2" 
      Grid.Row="2" 
      HorizontalAlignment="Center" 
      VerticalAlignment="Center" /> 

原來這是一個很容易解決。

+0

你知道這是爲什麼嗎?我很困惑,因爲datacontext已經在App.xaml的資源中定義爲「{Binding Main,Source = {StaticResource Locator}}」。 –

+0

如果我沒有記錯,TitleView.xaml通過App.xaml中的DataTemplate鏈接到TitleViewModel。 GameViewCommand在MainViewModel中,默認情況下不能被TitleView訪問。覆蓋按鈕的DataContext允許我綁定到MainViewModel中的命令。 –