在我的項目中,我有一個TitleView
和GameView
。當程序啓動時,顯示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?
如果提供額外的代碼會有幫助,請讓我知道。
您已將Button的command屬性綁定到您的GameViewCommand。 Xaml中還有哪些地方需要訪問? –
'GameViewCommand'在'MainViewModel'中。我想找到一種方法將該命令綁定到'TitleView'中的按鈕。這可能嗎? –
您是否考慮將它重構爲BaseViewModel作爲靜態成員並在那裏指定處理邏輯? –