Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix memory leak in ListView #1243

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 12 additions & 2 deletions src/Wpf.Ui/Controls/ListView/ListView.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ namespace Wpf.Ui.Controls;
/// </example>
public class ListView : System.Windows.Controls.ListView
{
private DependencyPropertyDescriptor? _descriptor;

/// <summary>Identifies the <see cref="ViewState"/> dependency property.</summary>
public static readonly DependencyProperty ViewStateProperty = DependencyProperty.Register(
nameof(ViewState),
Expand Down Expand Up @@ -62,21 +64,29 @@ protected virtual void OnViewStateChanged(DependencyPropertyChangedEventArgs e)
public ListView()
{
Loaded += OnLoaded;
Unloaded += OnUnloaded;
}

private void OnLoaded(object sender, RoutedEventArgs e)
{
Loaded -= OnLoaded; // prevent memory leaks

// Setup initial ViewState and hook into View property changes
var descriptor = DependencyPropertyDescriptor.FromProperty(
_descriptor = DependencyPropertyDescriptor.FromProperty(
System.Windows.Controls.ListView.ViewProperty,
typeof(System.Windows.Controls.ListView)
);
descriptor?.AddValueChanged(this, OnViewPropertyChanged);
_descriptor?.AddValueChanged(this, OnViewPropertyChanged);
UpdateViewState(); // set the initial state
}

private void OnUnloaded(object sender, RoutedEventArgs e)
{
Unloaded -= OnUnloaded;

_descriptor?.RemoveValueChanged(this, OnViewPropertyChanged);
}

private void OnViewPropertyChanged(object? sender, EventArgs e)
{
UpdateViewState();
Expand Down