繁体   English   中英

MVVM-XAML中不同类的访问命令

[英]MVVM - Access command from different class in XAML

在项目中,我有一个TitleViewGameView 程序启动时,将显示TitleView 用户单击一个按钮,将显示GameView 我正在使用包含MainViewModel MVVM Light,它具有可切换到所需视图的命令:

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下行放入TitleView.xaml ...

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

...我可以访问GameViewCommand ,但是不能访问任何本地命令。

如何在保持对本地命令的控制的同时获得对GameViewCommand的访问权限?

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

我已经解决了这个问题。 我所要做的就是:

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

原来,这是一个非常简单的修复。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM