我目前在使用 WPF TreeView 时遇到了一个奇怪的内存泄漏问题。当我选择 TreeView 中的一个项目时,相应的 ViewModel 被强制保存在 TreeView 的 EffectiveValueEntry[] 集合中。问题在于,即使 ViewModel 从其父集合中删除,它也不会被释放。
以下是一个简单的代码来重现此问题:
MainWindow.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; }
}
}
MainWindow.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仍然存在,没有被标记为垃圾回收。