开发者

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

开发者 https://www.devze.com 2023-02-05 13:27 出处:网络
According to this document, the following code causes a memory leak in WPF: myDataBinding = new Binding("Children.Count");

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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号