本文将创建一个示例项目,运行后探查内存,发现本应被垃圾回收的UI控件没有被回收。进一步发现是CollectionView导致控件不能被回收。最后,通过查看.NET Framework源代码,发现其实不是内存泄露,虚惊一场。
发现问题
创建一个用户控件GroupControl,有AddGroup(object header, object[] items)方法。这个方法就是创建一个GroupBox,设置Header和GroupBox里面的ListBox.ItemsSource。
GroupControl.xaml
<ContentControl x:Class="Gqqnbig.TranscendentKill.GroupControl"
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">
<ItemsControl Name="selectionGroupPanel" x:FieldModifier="private" HorizontalAlignment="Left" VerticalAlignment="Top"/>
</ContentControl>
GroupControl.xaml.cs
public partial class GroupControl
{
public GroupControl()
{
InitializeComponent();
}
public event SelectionChangedEventHandler SelectionChanged;
public void AddGroup(object header, object[] items)
{
GroupBox groupBox = new GroupBox();
groupBox.Header