【问题标题】:Remove event from ViewModel when the User Control is unloading卸载用户控件时从 ViewModel 中删除事件
【发布时间】:2017-07-26 09:41:01
【问题描述】:

在我的代码中,我在加载事件期间将我的 VM 上的一个事件附加到用户控件上的一个方法,现在我想在卸载用户控件时删除该事件,我该怎么做?

在虚拟机

public delegate bool CheckCondition();
public class VMClass
{
     event CheckCondition Check;
}

在用户控制下

public partial class AControl:UserControl
{
   public AControl()
   {
       InitializeComponent();
    Loaded += (s, e) =>
           VM.Check +=() => CheckingCode();
   }
   public VMClass VM => (VMClass)DataContext;
}

我正在考虑使用UnLoaded事件,但问题是在UnLoaded事件时,DataContext已经为null,所以无法取消订阅该事件,即:

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

不起作用,因为 VM 已经是 null UnLoaded

当卸载用户控件时,如何删除附加到VM.Check 的事件?

【问题讨论】:

  • 你不能在视图模型中使用事件;但是使用 Messenger.Register / Send 如下所述_所以你不会得到死链接marcominerva.wordpress.com/2014/06/25/…
  • 附注:事件应该遵循EventHandler委托模式。

标签: c# wpf events


【解决方案1】:

您可以使用DataContextChanged 事件。

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;
    }
}

【讨论】:

    猜你喜欢
    • 2016-11-28
    • 2021-10-05
    • 1970-01-01
    • 2010-09-16
    • 2011-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-10
    相关资源
    最近更新 更多