在 WPF C# 中关闭打开的页面
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19674421/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Close an opened page in WPF C#
提问by Kamal
I have opened a new page in my application.
我在我的应用程序中打开了一个新页面。
XAML
XAML
<MenuItem Header="Admin" IsTabStop="False">
<MenuItem x:Name="mi_ManageUsers" Header="Manage Users" Click="mi_ManageUsers_Click"/>
</MenuItem>
C#
C#
private void mi_ManageUsers_Click(object sender, RoutedEventArgs e)
{
ManageUsers newPage = new ManageUsers();
this.Content = newPage;
}
Now i have a button in my new page
现在我的新页面中有一个按钮
XAML
XAML
<Page x:Class="Billing.ManageUsers"
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"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300"
Title="ManageUsers">
<Grid>
<Button x:Name="btnClose" Content="Close" HorizontalAlignment="Left" Margin="185,219,0,0" VerticalAlignment="Top" Width="75" Click="btnClose_Click"/>
</Grid>
</Page>
C#
C#
private void btnClose_Click(object sender, RoutedEventArgs e)
{
//OnReturn(new ReturnEventArgs<string>(this.dataItem1TextBox.Text));
this.NavigationService.GoBack();
}
But the code is not working. I need to close this new page or go back to previos window by clicking the button
但是代码不起作用。我需要关闭这个新页面或点击按钮返回上一个窗口
回答by sthotakura
As I mentioned in my comment, when you do this.Content = newPage;you are notactually navigating to the page, instead you are changing the Contentof the current page. When I tried your code, I was getting InvalidOperationExceptionon the line this.NavigationService.GoBack();.
正如我在我的评论中提到,当你做this.Content = newPage;你不实际浏览的网页,而不是你正在改变Content当前页面的。当我尝试您的代码时,我正在InvalidOperationException上线this.NavigationService.GoBack();。
To get it working, change code in your mi_ManageUsers_Clickmethod to:
要使其正常工作,请将mi_ManageUsers_Click方法中的代码更改为:
NavigationService.Navigate(new ManageUsers());
I have tested this code and works. Hope this helps.
我已经测试了这段代码并且有效。希望这可以帮助。

