簡體   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