简体   繁体   English

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

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

In my project I have a TitleView and GameView . 在项目中,我有一个TitleViewGameView When the program launches, TitleView is displayed. 程序启动时,将显示TitleView The user clicks a button and GameView is displayed. 用户单击一个按钮,将显示GameView I am using MVVM Light which includes MainViewModel which has commands to switch to the desired views: 我正在使用包含MainViewModel MVVM Light,它具有可切换到所需视图的命令:

From MainViewModel.cs MainViewModel.cs

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

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

In TitleView.xaml, I need to access this command and I don't know how. 在TitleView.xaml中,我需要访问此命令,但我不知道如何操作。 I am very much a novice when it comes to XAML. 关于XAML,我非常新手。

From TitleView.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" />

If I put the following line into TitleView.xaml ... 如果我TitleView.xaml下行放入TitleView.xaml ...

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

... I can access GameViewCommand , but I can't access any local commands. ...我可以访问GameViewCommand ,但是不能访问任何本地命令。

What can I do to gain access to GameViewCommand while maintaining control of local commands? 如何在保持对本地命令的控制的同时获得对GameViewCommand的访问权限?

If providing additional code would be helpful, please let me know. 如果提供其他代码有帮助,请告诉我。

I've fixed the problem. 我已经解决了这个问题。 All I had to was this: 我所要做的就是:

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

Turns out it was a very easy fix. 原来,这是一个非常简单的修复。

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

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