【发布时间】:2018-04-30 08:38:40
【问题描述】:
您好,我正在制作 WPF 应用程序。
我有一个主窗口,其中有我的导航,然后我还有一个堆栈面板,其中:
<Frame x:Name="_mainFrame" NavigationUIVisibility="Hidden"/>
里面,我把我的页面放在里面。
在我的主窗口中,我使用以下命令导航到其他页面,例如移动到游戏窗口:
private void NavigateGameWindow(object sender, RoutedEventArgs e)
{
_mainFrame.Navigate(new GameWindow());
}
这工作正常,但现在我在那个窗口(gameWindow)内,我正在检查是否设置了“玩家”,如果没有,我想导航到另一个页面,在那里我可以设置某些值。 然后导航回 GameWindow。
但是当 _mainFrame 是主窗口的一部分时,我如何获得它?
它在 _mainFrame 上的 GameWindow 中显示
The name _mainFrame, does not exist in the current context
游戏窗口
public partial class GameWindow
{
private int numberOfPlayers;
private Player[] players;
private INavigator _navigator;
public GameWindow(INavigator navigator)
{
_navigator = navigator; //assign navigator so i can navigate _mainframe to other pages.
// initialize game properties, check if they are set.
var gameProp = new GameProperties();
this.numberOfPlayers = 2;
this.players = gameProp.CheckPlayerIsSet(this.players);
//check if a player has been set
if (this.players != null)
{ // Player is set or has been set. proceed or start the game.
InitializeComponent();
}
else
{ // redirect to settings window because players has not been set!
_navigator.Navigate(new GameSettings());
}
}
}
主窗口
public partial class MainWindow : Window, INavigator
{
public MainWindow()
{
InitializeComponent();
}
private void ExitGame(object sender, RoutedEventArgs e)
{
System.Windows.Application.Current.Shutdown();
}
public void Navigate(Page p)
{
_mainFrame.Navigate(p);
}
private void NavigateRulesWindow(object sender, RoutedEventArgs e)
{
Navigate(new GameRulesWindow());
}
private void NavigateGameWindow(object sender, RoutedEventArgs e)
{
Navigate(new GameWindow(this));
}
}
游戏设置
public partial class GameSettings : Page
{
public GameSettings()
{
InitializeComponent();
//var gameProps = new GameProperties();
// set number of players,, should prompt user, and get value!
//gameProps.SetNumberOfPlayers(2);
}
}
查看游戏设置
<Page x:Class="ITD.OOP_Projekt.WPF.Menu.GameSettings"
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:local="clr-namespace:ITD.OOP_Projekt.WPF.Menu"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800"
Title="GameSettings">
<Grid Background="white">
<TextBox HorizontalAlignment="Left" Height="23" Margin="229,144,0,0" TextWrapping="Wrap" Text="This is game settings" VerticalAlignment="Top" Width="120"/>
</Grid>
</Page>
【问题讨论】:
-
你在哪里得到这个错误?我的意思是代码的哪一部分?
-
你应该正确和重要的代码块,这里没有人能理解你得到的确切问题。
-
我要求分享所有必需的代码块。你得到的名字_mainFrame,在当前上下文中不存在这个错误
-
@GaurangDave 当我尝试使用与navigationgamewindow 相同的代码和_mainframe 时,它就是这么说的。
-
我认为至少有人应该提到这种方法是不寻常的。 MVVM 是 WPF 的事实标准,我建议您考虑一下。一种简单的导航方法是首先使用 viewmodel。还。除了 wpf 应用程序的初学者外,很少有人使用页面。 Contentcontrol 和 usercontrol 会更常见。