c# - OnDetaching function of behavior is not called -
i have wpf behavior
on specific control. when close window hold control ondetaching
function not called.
the behavior continues exist (because of events it's registered), although window not exist anymore (memory leak).
why ondetaching
function not fired****, , how can solve it?
protected override void onattached() { base.onattached(); this.associatedobject.mouseleftbuttondown += associatedobject_plotareamouseleftbuttondown; this.associatedobject.mouseleftbuttonup += associatedobject_plotareamouseleftbuttonup; this.associatedobject.mousemove += associatedobject_plotareamousemove; } protected override void ondetaching() { base.ondetaching(); this.associatedobject.mouseleftbuttondown -= associatedobject_plotareamouseleftbuttondown; this.associatedobject.mouseleftbuttonup -= associatedobject_plotareamouseleftbuttonup; this.associatedobject.mousemove -= associatedobject_plotareamousemove; }
the onattached
called when xaml parser parses xaml , creates instance of behaviour adds behaviorcollection of target control exposed dependencyattached property.
however when if view disposed, collection (behavior collection) disposed of, it never trigger ondetaching method.
if behaviour not cleanup not collected gc , hold behaviorcollection , other behaviors in collection. behaviours designed extend associatedobject, long subscribing associatedobject events fine associatedobject (publisher) die , behaviour collected garbage collector.
an alternative handle "closing" event (when user clicks upper right 'x' button) of window, , ondetaching
there.
<i:interaction.triggers> <i:eventtrigger eventname="closing"> <cmd:eventtocommand command="{binding closecommand}" /> </i:eventtrigger> </i:interaction.triggers>
then associate handler in view constructor:
mywindow() { // set viewmodel, assign datacontext etc. closing += viewmodel.onwindowclosing; }
and add handler viewmodel:
public void onwindowclosing(object sender, canceleventargs e) { // cancel, ondetaching, etc }
Comments
Post a Comment