Graviton
Graviton

Reputation: 83254

Remove event from ViewModel when the User Control is unloading

In my code, I am attaching an event at my VM to a method at the user control during at loaded event, now I want to remove the event when the user control is unloaded, how can I do 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 am thinking about using UnLoaded event, but the problem is that at the UnLoaded event, DataContext is already null, so I can't unsubscribe the event, ie:

   UnLoaded +=(s, e) =>
               VM.Check -=() => CheckingCode(); 

Doesn't work because VM is already a null at UnLoaded .

How can I remove the event attached to VM.Check when the user control is unloaded?

Upvotes: 2

Views: 763

Answers (1)

Sharada
Sharada

Reputation: 13601

You can use DataContextChanged event.

DataContextChanged += (object sender, DependencyPropertyChangedEventArgs e) =>
{
    var oldVM = e.OldValue as VMClass;
    var newVM = e.NewValue as VMClass;

    if (oldVM != null)
    {
        oldVM.Check -= CheckingCode;
    }

    if (newVM != null)
    {
        newVM.Check += CheckingCode;
    }
}

Upvotes: 4

Related Questions