引发事件,每当一个属性值改变?

问题描述:

有一种属性,它的命名 ImageFullPath1

There is a property, it's named ImageFullPath1

public string ImageFullPath1 {get; set; }

我要火,只要它的价值变化的事件。我知道我可以提防与 INotifyPropertyChanged的改变,但我想这样做与事件。
我不知道我应该怎么做。
能否请你指导我?

I'm gonna fire an event whenever its value changed. I know I can beware of changing with INotifyPropertyChanged, but I wanna do it with events.
I don't know how I should do it.
Could you please guide me?

感谢。

INotifyPropertyChanged的接口与事件实现。该接口有一个成员,的PropertyChanged ,它是一个事件,消费者可以订阅

The INotifyPropertyChanged interface is implemented with events. The interface has just one member, PropertyChanged, which is an event that consumers can subscribe to.

这是理查德发布的版本是不是安全。下面是如何安全地实现这个接口:

The version that Richard posted is not safe. Here is how to safely implement this interface:

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

请注意,这样做以下几件事:

Note that this does the following things:

  • 抽象化属性更改通知方式,因此您可以轻松地应用这等性能;

  • Abstracts the property-change notification methods so you can easily apply this to other properties;

在使的PropertyChanged 委托的副本试图调用它(如果不这样做会创建一个竞争条件)。

Makes a copy of the PropertyChanged delegate before attempting to invoke it (failing to do this will create a race condition).

正确实施 INotifyPropertyChanged的接口。

如果你想的此外的创建通知了的的具体的性质被改变,你可以添加以下code:

If you want to additionally create a notification for a specific property being changed, you can add the following code:

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

public event EventHandler ImageFullPathChanged;

然后添加一行 OnImageFullPathChanged(EventArgs.Empty)行之后 OnPropertyChanged(ImageFullPath)