Reputation: 175
Two questions:
Is it possible to cause a memory leak if I replace a Binding
in a Trigger
? For example, if my Text
property bound to some dependency property, and in a trigger I set a different binding on Text
, like in the example below, is there a chance for a leak?
<DataTemplate>
<TextBlock x:Name="myTextBlock" Text={Binding PropertyX} />
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding Path=IsPressed}" Value="True">
<Setter TargetName="myTextBlock"
Property="Text"
Value="{Binding PropertyX, StringFormat={}{0} is too damn high}"/>
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
Maybe some kind of "abandoned" binding? I know that if I bind to non-dependency property/object, then I'll have a leak, but will the scenario above cause a leak?
I read somewhere (and I can't find it right now) that there are scenarios where if you give to an element the property x:Name
then you may cause to memory leak. What are those cases? I believe that naming my elements in my templates is totally OK.
Thanks!
Upvotes: 0
Views: 261
Reputation: 25623
Is it possible to cause memory leak if I change the binding by trigger.
In general, there's no more potential for a leak than there would be with just a single binding. That's not to say that a leak is impossible, but if you follow the best practices and make sure anything you bind to implements INotifyPropertyChanged
, then you won't accidentally cause your binding source to be retained. Binding expressions use weak references to refer to the bound object, so that won't cause a leak.
Specifically, the example you posted looks fine, and should not cause a leak.
I read somewhere (and I can't find it right now) that there are scenarios where if you give to an element the property x:Name then you may cause to memory leak.
The case would be when you remove an element with an x:Name
directive from your UI tree. The reason is that x:Name
doesn't just set the Name
property; it also registers the element in the name scope, and that registration involves a strong reference. If you remove a named element from the UI without also removing it from the name scope, then it will be kept alive until the name scope becomes unreachable.
When removing a named element, call UnregisterName
in the parent view, passing in the name of the element you are removing. That will remove it from the name scope.
Upvotes: 2