Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 629
Andrew Orsich Avatar asked Jan 20 '11 15:01

Andrew Orsich


2 Answers

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.

like image 193
Marat Khasanov Avatar answered Oct 24 '22 00:10

Marat Khasanov


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.

like image 4
Aaron McIver Avatar answered Oct 23 '22 22:10

Aaron McIver