简体   繁体   中英

Close Window in WPF C#

I want to close a windows which is currently shown. But when I call Close() , it only hide the window. And the memory length still grows instead of decreasing.

I also use this answer to fix this problem:

https://stackoverflow.com/a/34651426/9135351

but it doesn't work.

Here is my code to show a new Window and close the shown Window

C#

private void Home_Click(object sender, RoutedEventArgs e)
{
   new HomeContentView().Show(); //Open Home window
   Close(); //Close current window
   GC.Collect(); //Realease
}

Xaml

 <Button
     ToolTip="Home"
     Click="Home_Click"
     Cursor="Hand"
     Background="Transparent"
     BorderBrush="Transparent"
     Margin="0,0,221,0"
     HorizontalAlignment="Right"
     Width="48" Height="48"
     VerticalAlignment="Top">

     <materialDesign:PackIcon Kind="Home" Width="37" Height="38" 
     Foreground="Black" HorizontalAlignment="Stretch" />
 </Button>

Close() should do the trick. Why can't you use the object created for the Window and Close that instead of accessing it from the Application.Current.Windows

var window = new HomeContentView(); 
window.Show(); // Shows window
window.Close(); // Closes window
public void MyMethod()
    {
        var myWindow = this;
        var control = myWindow.Content;
        //do stuff
        control = null; // is that okay??
        myWindow.Close();
    }

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