WPF DataGrid 无法被释放?

晚安苏州 2018-07-02 11:24:13
遇到奇怪的现象,只要在界面里加入DataGrid控件,界面内存实例就无法释放,举个例子:

在界面 MainWindow 里弹出一个新窗体 Window1:

<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApplication1"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525" >
<Grid>
<Button x:Name="button" Content="Button" HorizontalAlignment="Left" Margin="215,137,0,0" Click="button_Click"
VerticalAlignment="Top" Width="75"/>
</Grid>
</Window>




private void button_Click(object sender, RoutedEventArgs e)
{
Window1 w1 = new Window1();
w1.ShowDialog();
}


1.首先,新窗体Window1里啥控件都不放,默认的如下:

<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApplication1"
mc:Ignorable="d"
Title="Window1" Height="300" Width="300">
<Grid>

</Grid>
</Window>


弹出界面并关闭,操作数次之后,内存里是没有Window1这个实例的:


2.其次,我在Window1里加一个默认的DataGrid:

<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApplication1"
mc:Ignorable="d"
Title="Window1" Height="300" Width="300">
<Grid>
<DataGrid Width="200" Height="200" Background="Brown">

</DataGrid>
</Grid>
</Window>


弹出Window1界面并关闭,操作数次,最终关闭Window1界面,内存里始终是有Window1这个实例的:


真的是服了,总是遇到这些奇葩情况,为什么呢?是不是这种弹出窗体做法不对?我手动释放 ,调用GC回收也不行:

private void button_Click(object sender, RoutedEventArgs e)
{
Window1 w1 = new Window1();
w1.ShowDialog();

w1 = null;
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}


请高人指点

...全文
695 3 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
晚安苏州 2018-07-02
  • 打赏
  • 举报
回复
引用 1 楼 qq14923349 的回复:
gc不会马上生效的~~


问题是为什么不加DataGrid , 也不去手动调用GC回收,就没有上面的问题呢?感觉问题就出在加入了这个 DataGrid 控件
qq14923349 2018-07-02
  • 打赏
  • 举报
回复
Window1 w1 = new Window1();
w1.ShowDialog();

w1 = null;
完全没问题
qq14923349 2018-07-02
  • 打赏
  • 举报
回复
gc不会马上生效的~~

8,756

社区成员

发帖
与我相关
我的任务
社区描述
WPF/Silverlight相关讨论
社区管理员
  • WPF/Silverlight社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧