c# - Remove event from ViewModel when the User Control is unloading -
in code, attaching event @ vm method @ user control during @ loaded event, want remove event when user control unloaded, how can it?
at vm
public delegate bool checkcondition(); public class vmclass { event checkcondition check; } at user control
public partial class acontrol:usercontrol { public acontrol() { initializecomponent(); loaded += (s, e) => vm.check +=() => checkingcode(); } public vmclass vm => (vmclass)datacontext; } i thinking using unloaded event, problem @ unloaded event, datacontext null, can't unsubscribe event, ie:
unloaded +=(s, e) => vm.check -=() => checkingcode(); doesn't work because vm null @ unloaded .
how can remove event attached vm.check when user control unloaded?
you can use datacontextchanged event.
datacontextchanged += (object sender, dependencypropertychangedeventargs e) => { var oldvm = e.oldvalue vmclass; var newvm = e.newvalue vmclass; if (oldvm != null) { oldvm.check -= checkingcode; } if (newvm != null) { newvm.check += checkingcode; } }
Comments
Post a Comment