简体   繁体   English

模型属性更改时如何触发事件

[英]How to fire event if model property changes

I developing application using backround processes and MVP pattern. 我使用背景流程和MVP模式开发应用程序。 Can I store states of processes (isCanceled, isStarted or isPaused) in ModelProcess (Model) like this: 我可以像下面这样在ModelProcess(模型)中存储进程状态(isCanceled,isStarted或isPaused):

public event EventHandler CancelChanged;
  bool isCanceled = false;
    public bool IsCanceled
    {
        get { return isCanceled; }
        set
        {
            isCanceled = value;
            if (isCanceled)
            {
                if (CancelChanged != null)
                {
                    CancelChanged(this, EventArgs.Empty);
                }
            }
        }
    }

Your setter will only call CancelChanged if isCanceled is being set to true , no matter if it has been false before. 如果isCanceled设置为true ,则设置方法将仅调用CancelChanged ,无论之前是否为false The following code will check if there is an actual change of the value, wich makes it idempotent. 下面的代码将检查该值是否存在实际变化,并使其等幂。

set
{
    if (value != isCanceled)
    {
        isCanceled = value;
        if (CancelChanged != null)
        {
            CancelChanged(this, EventArgs.Empty);
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM