【发布时间】:2016-04-04 16:09:13
【问题描述】:
我正在使用 MVVMLight 创建调查问卷,并在呈现 InkCanvas 控件时遇到内存问题。这是我正在使用的一个淡化示例:
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());
}
每个页面加载时 RAM 都会出现峰值,很明显分配给 InkCanvas 的内存永远不会被释放。在第三页左右呈现大约 125 个 InkCanvas 控件时,应用程序会引发 System.OutOfMemoryException。
我的问题是,为什么不释放这些控件?以及如何手动释放内存?如果我注释掉 InkCanvas,则调查问卷很好,并且 Children.Clear() 似乎正在清理 TextBlocks 或任何其他控件而没有问题。
更新
因此,在与@Grace Feng 合作后,我尝试重构我的方法并使用带有数据模板的 ListView,而不是从我的 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();
}
}
不幸的是,即使使用 ListView 数据模板方法,我仍然遇到同样的内存不足错误。想法?
【问题讨论】:
标签: c# win-universal-app mvvm-light inkcanvas