I'm using MVVMLight to create a questionnaire and running into memory issues when rendering the InkCanvas controls. Here's a watered down example of what I am working with:
QuestionVm
public Question Question { get; set; }
public HandwritingControl HandwritingControl { get; set; }
QuestionnaireVm
public List<QuestionVm> currentQuestions;
public List<QuestionVm> CurrentQuestions
{
get { return currentQuestions; }
set
{
currentQuestions = value;
RaisePropertyChanged();
}
}
Questionnaire.xaml.cs
//Clear form & iterate questions
questionnaireForm.Children.Clear();
foreach (var questionVm in questionnaireVm.CurrentQuestions)
{
questionnaireForm.Children.Add(questionVm.Question);
if(questionVm.HandwritingControl != null)
questionnaireForm.Children.Add(new InkCanvas());
}
The RAM spikes on each page load and it's clear the memory allocated to the InkCanvas is never being deallocated. On the third or so page when roughly ~125 InkCanvas controls are rendered, the app throws a System.OutOfMemoryException.
My question is, why aren't these controls being deallocated? And how can I manually free up the memory? If I comment out the InkCanvas, the questionnaire is fine and Children.Clear() appears to be cleaning up the TextBlocks or any other controls without issue.
UPDATE
So after working with @Grace Feng I tried to refactor my approach and use a ListView with a data template rather than creating a grid from my xaml.cs.
Questionnaire.xaml
<ListView Name="questionnaireListView" ItemsSource="{Binding CurrentQuestions, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Question.Text}" />
<TextBlock Text="{Binding Question.Description}" />
<InkCanvas/>
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Questionnaire.xaml.cs
private void buttonNext_Click(object sender, RoutedEventArgs e)
{
//Validate & goto next page
if (questionnaireVm.CurrentPageIsValid())
{
questionnaireVm.CurrentQuestions.Clear();
questionnaireVm.LoadNextPage();
}
}
Unfortunately I am still experiencing the same out of memory error even using the ListView data template method. Thoughts?