1

在我的项目中,我有一个TitleViewand GameView。程序启动时,TitleView显示 。用户单击按钮并GameView显示。我正在使用 MVVM Light,其中包括MainViewModel哪些命令可以切换到所需的视图:

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?

如果提供其他代码会有所帮助,请告诉我。

4

1 回答 1

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" />

事实证明这是一个非常容易解决的问题。

于 2013-06-03T01:21:52.467 回答