'Is there any way to remove bindings from all bound elements on a form close event?

According to this document, the following code causes a memory leak in WPF:

myDataBinding = new Binding("Children.Count");
myDataBinding.Source = myGrid; 
myDataBinding.Mode = BindingMode.OneWay;
MyTextBlock.SetBinding(TextBlock.TextProperty, myDataBinding);

The same happens if we bind some value in XAML:

<TextBlock Name="MyTextBlock" 
           Text="{Binding ElementName=myGrid, Path=Children.Count}" />

To avoid binding memory leaks we need to remove binding on the form close event like this:

BindingOperations.ClearBinding(MyTextBlock, TextBlock.TextProperty);

Question:

Is there a way to remove bindings from all bound elements on form and child controls?

It seems I would need some recursive method here.



Solution 1:[1]

Keep in mind that the example given was very isolated and not typical in a binding situation. The referenced document outlines this...

The TextBlock control has a binding to an object (myGrid) that has a reference back to the TextBlock (it is one of myGrid children’s).

The problem lies in the fact that the binding is taking place across UIElement objects AND one of the objects is a child of the container AND the propety being binded to is not a DependencyProperty. Again this is not typical as most binding occurs on an object/property which implements INotifyPropertyChanged.

If you have multiple bindings like this within your application then the approach should be to clear them out as needed when the given container closes as mentioned in the referenced document.

Another approach is to simply expose the data you need on your object being consumed by the View and disregard binding to the UIElement properties which are not of type DependencyPrperty. While this is not always practical it will alleviate you from the above mentioned problem.

Solution 2:[2]

In WPF 4 you may don't worry about leaks when binding to an object even if it is not INotifyPropertyChanged or DependencyObject. This bug was fixed.

Anyway I suppose BindingOperations.ClearAllBindings will be helpful.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Marat Khasanov