【问题标题】:WPF Unbind all elements and their sub elements from any bindingsWPF 从任何绑定中取消绑定所有元素及其子元素
【发布时间】:2015-11-19 21:13:45
【问题描述】:

我想防止基于绑定到Static 成员或...在我的WPF Window 中的一些内存泄漏。

此窗口包含许多UserControlelement 并有一些static 资源。 我知道我应该 unbind bindingsStatic 类来防止一些内存泄漏,我知道这种unbinding

BindingOperations.ClearAllBindings(....);

BindingOperations.ClearBinding(...., ....);

Element.ItemsSource= null;

但我的问题是:

你知道或推荐任何 自动 Unbind 系统(一些类和代码作为一种机制来解除所有元素的绑定以在需要时调用它)在我们想要关闭窗口时使用它确保没有任何绑定到Window 或其UserControls 及其elements 和任何sub-elements 中的任何元素???

我正在寻找一种安全的方式在窗口关闭事件中使用...

【问题讨论】:

    标签: c# wpf data-binding memory-leaks unbind


    【解决方案1】:

    我不相信有一种自动的方法可以做到这一点,但我为此在DependencyObject 上定义了我自己的扩展方法。

    public static IEnumerable<DependencyObject> EnumerateVisualChildren(this DependencyObject dependencyObject)
    {
        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(dependencyObject); i++)
        {
            yield return VisualTreeHelper.GetChild(dependencyObject, i);
        }
    }
    
    public static IEnumerable<DependencyObject> EnumerateVisualDescendents(this DependencyObject dependencyObject)
    {
        yield return dependencyObject;
    
        foreach (DependencyObject child in dependencyObject.EnumerateVisualChildren())
        {
            foreach (DependencyObject descendent in child.EnumerateVisualDescendents())
            {
                yield return descendent;
            }
        }
    }
    
    public static void ClearBindings(this DependencyObject dependencyObject)
    {
        foreach (DependencyObject element in dependencyObject.EnumerateVisualDescendents())
        {
            BindingOperations.ClearAllBindings(element);
        }
    }
    

    【讨论】:

    • 谢谢你。我的意思是像您的解决方案这样的机制,它使unbinding all 成为自动工作。但是您如何看待您的代码?仅在 DependencyObjects 的 2 级工作?
    • EnumerateVisualDescendents 是一个递归函数,请参见:child.EnumerateVisualDescendents() 在内部 foreach 中
    • 是的,它是一个递归函数。您对此代码的性能和速度有何反馈?
    • 我并没有真正直接测试性能,我唯一能说的是我在打开应用程序中的每个窗口时都在运行类似的方法(更新所有绑定)。没有明显的延迟
    • @RAM 我刚刚在代码顶部添加了方法
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-16
    • 1970-01-01
    • 2014-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多