简体   繁体   English

在Windows WPF(MVC)之间切换

[英]Switching Between Windows WPF (MVC)

I have a test WPF application that has two windows (I'm also using MVC and not MVVM). 我有一个具有两个窗口的WPF测试应用程序(我也在使用MVC,而不是MVVM)。 Both which have one button that should direct the user to the other window. 两者都有一个按钮,应将用户定向到另一窗口。

Initially, I tried this code (I'm only showing the event handlers): 最初,我尝试了以下代码(我仅显示事件处理程序):

MainWindow.xaml.cs MainWindow.xaml.cs

private static void Button_Click(object sender, RoutedEventArgs e)
{
    OtherWindow k = new OtherWindow();
    k.Show();
    this.Close();
}

OtherWindow.xaml.cs OtherWindow.xaml.cs

private static void Button_Click(object sender, RoutedEventArgs e)
{
    MainWindow k = new MainWindow();
    k.Show();
    this.Close();
}

The code works, but I take a look at the memory usage and it increases every time I switch window. 该代码有效,但是我看一下内存使用情况,并且每次切换窗口时它都会增加。 Is this normal or is there a way to avoid this and keep the simplicity? 这是正常现象还是有避免这种情况并保持简单性的方法?

It's very easy to run into memory leaks in WPF, especially when instantiating and disposing of windows multiple times. 在WPF中很容易遇到内存泄漏,尤其是在多次实例化和处置Windows时。

I'd recommend taking a look at this page: 我建议您看一下此页面:

http://svetoslavsavov.blogspot.com/2010/05/memory-leaks-in-wpf-applications.html http://svetoslavsavov.blogspot.com/2010/05/memory-leaks-in-wpf-applications.html

which details the most common ways to run into a memory leak in WPF and how to fix it. 其中详细介绍了在WPF中遇到内存泄漏的最常见方法以及解决方法。

I'd suggest looking at the Event Handlers and Events from Static Objects sections first. 我建议先查看“静态对象中的事件处理程序和事件”部分。

It seems that you aren't removing your event handlers for your window before closing it, which means that the Window will be kept in memory. 似乎您没有在关闭窗口之前删除事件处理程序,这意味着该窗口将保留在内存中。

You should also take a look at this thread for good points on disposing of resources correctly. 您还应该查看此线程,以获取正确处理资源的优点。 Check out the answer by rookie1024: What is the correct way to dispose of a WPF window? 看看rookie1024的答案: 处置WPF窗口的正确方法是什么?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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