Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory leaks while scrolling in WPF VirtualizingStackPanel

Am using VirtualizingStackPanel and textBlock, my XAML code looks like below,

<Grid>
    <ItemsControl Name="NameItemsControl"
VirtualizingStackPanel.IsVirtualizing="True"
ScrollViewer.CanContentScroll="True"
ItemsSource="{Binding Path=NameList}">

        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Path=TaskName}" />
            </DataTemplate>
        </ItemsControl.ItemTemplate>
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <VirtualizingStackPanel />
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
        <ItemsControl.Template>
            <ControlTemplate>
                <Border>
                    <ScrollViewer>
                        <ItemsPresenter />
                    </ScrollViewer>
                </Border>
            </ControlTemplate>
        </ItemsControl.Template>
    </ItemsControl>
</Grid>

In .cs i have below code,

public partial class MainWindow : Window
{
    private List<Task> Tasks;
    public MainWindow()
    {
        InitializeComponent();
        Tasks = new List<Task>();

        for (int i = 1; i < 1000; i++)
        {
            Task task = new Task() { TaskName = "Task " + i, Id = i, Size = 20 };

            Tasks.Add(task);
        }
        NameItemsControl.ItemsSource = Tasks;
    }
}
public class Task 
{
    public string TaskName { get; set; }
    public int Id { get; set; }
    public int Size { get; set; }
} 

I can see memory leak while scrolling, Am using VS 2013 Performance and Diagnostics to track the leak. This is what i see in the Managed Heap enter image description here

It shows that ConditionalWeakTable<Object,Object> count is increasing while scrolling. Is there any way to fix this issue? For some reason i don't want to set

VirtualizingStackPanel.VirtualizationMode="Recycling"
like image 330
Amar Avatar asked Apr 26 '26 01:04

Amar


1 Answers

Set VirtualizingStackPanel.VirtualizationMode="Recycling" on the ItemsControl to avoid the memory leak. I had the same issue in this scenario and setting VirtualizingStackPanel.VirtualizationMode="Recycling" resolved the problem.

<ItemsControl Name="NameItemsControl"
VirtualizingStackPanel.VirtualizationMode="Recycling"
ScrollViewer.CanContentScroll="True"
ItemsSource="{Binding Path=NameList}">
like image 142
Rana Ian Avatar answered Apr 29 '26 07:04

Rana Ian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!