現在、WPF TreeViewで奇妙なメモリリークが発生しています。 TreeViewでアイテムを選択すると、対応するバインドされたViewModelがTreeView EffectiveValueEntry []コレクションで強く保持されます。問題は、ViewModelが親コレクションから削除されたときに解放されないことです。ここでWPFツリービューで選択したアイテムが漏洩しています
は、問題を再現するための簡単なコードです:
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はまだ存在し、ガベージコレクションのフラグが設定されていません。
あなたは何の.Netバージョンを使用している次のようにありますか? – JleruOHeP
私は.NET 3.5と4.0で問題があります。私はそれについて言及することを完全に忘れました、申し訳ありません。私は今すぐ4.5でテストします。 – Sisyphe
.NET 4.5にはまだ問題があります – Sisyphe