绑定到WPF TreeView时发生内存泄漏 [英] Memory leak on binding to a WPF TreeView

查看:119
本文介绍了绑定到WPF TreeView时发生内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们遇到了一个问题,即TreeView挂在绑定到它的视图模型集上.我们在主窗口上有一个静态树视图,并在需要显示新内容时将其ItemsSource重置为Nothing或新的视图模型.问题似乎 即使在ItemsSource设置为nothing之后,它仍挂在它绑定到的第一个项目上.这种连接似乎是通过TreeView的EffectiveValues集合中的一些奇怪的未知绑定进行的.

We're having an issue with a TreeView hanging onto a viewmodel set that has been bound to it. We have a static treeview on the main window, and reset its ItemsSource to Nothing or a new viewmodel when new things need to be displayed. The problem seems to be that it's hanging onto the first item that it was bound to, even after the ItemsSource is set to nothing. The connection seems to be through some strange unknown binding that's in the EffectiveValues collection of the TreeView.

 

我能够在测试项目中对此进行复制,因此我将发布简化的代码:

I was able to repro this in a test project, so I'll post the simplified code:

 

TreeView模板:

TreeView templates:

 

 <Window.Resources>
  <HierarchicalDataTemplate DataType="{x:Type local:ParentViewModel}"
         ItemsSource="{Binding ChildVMs}">
   <TextBlock Text="{Binding Name}"/>
  </HierarchicalDataTemplate>
  <DataTemplate DataType="{x:Type local:ChildViewModel}">
   <TextBlock Text="{Binding Name}"/>   
  </DataTemplate>  
 </Window.Resources>

推荐答案

乔什,你好,

以下博客介绍了许多有关WPF中内存泄漏的情况,一种是用于数据绑定. http://blogs.msdn.com/b/jgoldb/archive/2008/02/04/finding-memory-leaks-in-wpf-based-applications.aspx  其他类似下面的知识库文章: http://support.microsoft.com/kb/938416/en-us  引入了相同的内容.

the following blog introduces many scenarios about the memory leak in WPF, one is for Data Binding. http://blogs.msdn.com/b/jgoldb/archive/2008/02/04/finding-memory-leaks-in-wpf-based-applications.aspx others like the following KB article: http://support.microsoft.com/kb/938416/en-us that introduces the same content.

在阅读了文章之后,我们可以尝试两种解决方法:

Well, after reading the articles, we have two workarounds we can try:

  • Clear the DataBinding by BindingOperations.ClearBinding method after unload the source. However, it is not easy to get the bound elements in the TreeView.
  • Set the DataBinding as OneTime mode.

然后myTreeView.EffectiveValues.LocalValue是DependencyProperty.UnsetValue.

Then the myTreeView.EffectiveValues.LocalValue are the DependencyProperty.UnsetValue.

此致
鲍勃

MSDN论坛中的订阅者支持

如果您对我们的支持有任何反馈,请联系 msdnmg@microsoft.com

If you have any feedback on our support, please contact msdnmg@microsoft.com

 


这篇关于绑定到WPF TreeView时发生内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆