问题描述
我们遇到了一个问题,即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:
- 通过清除数据绑定卸载源后的BindingOperations.ClearBinding 方法.但是,在TreeView中获取绑定元素并不容易.
- 将DataBinding设置为OneTime模式.
- 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.
此致
鲍勃
如果您对我们的支持有任何反馈,请联系 msdnmg@microsoft.com
If you have any feedback on our support, please contactmsdnmg@microsoft.com
这篇关于绑定到WPF TreeView时发生内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!