我目前有一个奇怪的 WPF TreeView 内存泄漏。当我在 TreeView 中选择一个项目时,对应的绑定 ViewModel 强烈地保存在 TreeView EffectiveValueEntry[] 集合中。问题是当 ViewModel 从其父集合中删除时它不会被释放。
这是重现该问题的简单代码:
主窗口.xaml
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Controls.Primitives;
namespace TreeViewMemoryLeak
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = this;
}
public ObservableCollection<Entry> Entries
{
get
{
if (entries == null)
{
entries = new ObservableCollection<Entry>() { new Entry() { DisplayName = "First Entry" } };
}
return entries;
}
}
private void Button_Click(object sender, RoutedEventArgs e) { entries.Clear(); }
private ObservableCollection<Entry> entries;
}
public class Entry : DependencyObject
{
public string DisplayName { get; set; }
}
}
主窗口.xaml.cs
<Window x:Class="TreeViewMemoryLeak.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:TreeViewMemoryLeak"
Title="MainWindow" Height="350" Width="250">
<Window.Resources>
<DataTemplate DataType="{x:Type local:Entry}">
<TextBlock Text="{Binding DisplayName}" />
</DataTemplate>
</Window.Resources>
<StackPanel>
<Button Content="delete item" Click="Button_Click" Grid.Row="0" Margin="10"/>
<TreeView x:Name="treeView" ItemsSource="{Binding Entries}" Grid.Row="1" Margin="10" BorderBrush="Black" BorderThickness="1" />
</StackPanel>
</Window>
重现问题
选择项目,然后单击按钮以清除 ObservableCollection。现在检查 TreeView 控件上的 EffectiveValueEntry[]:ViewModel 仍然存在并且没有标记为垃圾回收。