There is a property, it's named ImageFullPath1

public string ImageFullPath1 {get; set; }

I'm going fire an event whenever its value changed. I am aware of changing INotifyPropertyChanged, but I want to do it with events.

推荐答案

INotifyPropertyChanged接口is通过事件实现.该接口只有一个成员PropertyChanged,这是一个消费者可以订阅的事件.

Richard发布的版本不安全.以下是如何安全地实现此接口:

public class MyClass : INotifyPropertyChanged
{
    private string imageFullPath;

    protected void OnPropertyChanged(PropertyChangedEventArgs e)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
            handler(this, e);
    }

    protected void OnPropertyChanged(string propertyName)
    {
        OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
    }

    public string ImageFullPath
    {
        get { return imageFullPath; }
        set
        {
            if (value != imageFullPath)
            {
                imageFullPath = value;
                OnPropertyChanged("ImageFullPath");
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

请注意,这将执行以下操作:

  • 抽象属性更改通知方法,以便您可以轻松地将其应用于其他属性;

  • 复制试图调用它的PropertyChanged个委托before(如果不这样做,将产生竞争条件).

  • 正确实现INotifyPropertyChanged接口.

如果要additionally为正在更改的specific属性创建通知,可以添加以下代码:

protected void OnImageFullPathChanged(EventArgs e)
{
    EventHandler handler = ImageFullPathChanged;
    if (handler != null)
        handler(this, e);
}

public event EventHandler ImageFullPathChanged;

然后在第OnPropertyChanged("ImageFullPath")行之后添加第OnImageFullPathChanged(EventArgs.Empty)行.

既然我们有.Net 4.5存在CallerMemberAttribute,它允许在源代码中go 掉属性名称的硬编码字符串:

    protected void OnPropertyChanged(
        [System.Runtime.CompilerServices.CallerMemberName] string propertyName = "")
    {
        OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
    }

    public string ImageFullPath
    {
        get { return imageFullPath; }
        set
        {
            if (value != imageFullPath)
            {
                imageFullPath = value;
                OnPropertyChanged();
            }
        }
    }

.net相关问答推荐

使用托管身份而不是检测密钥配置Application Insights

如何在dotnet中使用OpenTelemetry Prometheus导出器导出多个版本的度量?

Dotnet 反射:使用 F# 中的out参数调用 MethodInfo 上的调用

通过 System.Net.Mail 的 VB SMTP 停止工作

在 C# 中,如何使用泛型的基类将泛型接口的所有实例注入到单个构造函数中?

将日期时间转换为日期格式 dd/mm/yyyy

每当属性值发生变化时引发事件?

"投掷;" 是什么意思?靠自己做什么?

.NET 中的线程安全集合

在 Moq 中模拟泛型方法而不指定 T

将笔画应用于 WPF 中的文本块

哪个单元测试框架?

ASP.NET Core (.NET Core) 和 ASP.NET Core (.NET Framework) 的区别

如何从 XDocument 获取 Xml 作为字符串?

beforefieldinit 标志有什么作用?

将日期时间转换为时间跨度

说明 C# 中 volatile 关键字的用法

判断对象列表是否包含具有特定值的属性

从字节数组中读取 C# 中的 C/C++ 数据 struct

如何使用 NPOI 读取文件