简体   繁体   中英

Close an opened page in WPF C#

I have opened a new page in my application.

XAML

        <MenuItem Header="Admin" IsTabStop="False">
            <MenuItem x:Name="mi_ManageUsers" Header="Manage Users" Click="mi_ManageUsers_Click"/>
        </MenuItem>

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

<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#

    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

As I mentioned in my comment, when you do this.Content = newPage; you are not actually navigating to the page, instead you are changing the Content of the current page. When I tried your code, I was getting InvalidOperationException on the line this.NavigationService.GoBack(); .

To get it working, change code in your mi_ManageUsers_Click method to:

NavigationService.Navigate(new ManageUsers());

I have tested this code and works. Hope this helps.

我为此苦苦挣扎,但我终于找到了答案......要从您打开的页面中关闭页面,请使用:

 NavigationService.Navigate(null);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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