事件处理 - Visual Studio

Event handling - Visual Studio

我遇到了如下所述的问题。我是 .NET/Visual Studio (2013) 的新手,我想弄清楚为什么下面的代码不起作用。

我关注class

public class PropertySettings
{
    ...

    // get single instance of this class
    public static PropertySettings Instance
    {
        get { return thisInstance; }
    }

    // event declaration
    public event EventHandler<MyObj> PropertyChanged;

    ...

    public void SaveProperty(string propertyName, object obj)
    {
        var oldValue = obj.OldVal;
        var newValue = obj.NewVal;

        // Why is PropertyChanged event always null?
        if (PropertyChanged != null && oldValue != newValue)
        {
            PropertyChanged(this, obj); // pass reference to itself
        }
    }
}

SaveProperty 方法正在检查 PropertyChanged != null,如果是,它通过传递对自身和 obj 的引用来调用它。

然后从其他 class 调用 SaveProperty 方法,如下所示:

PropertySettings.Instance.SaveProperty("Width", Width);

我遇到的问题是 PropertyChanged 始终为空,因此从不调用 PropertyChanged 事件。

如果您有 class 的实例:

var x = new PropertySettings();

那么您需要 "wire up" 像这样的任何事件处理程序:

// "wire up" AKA "subscribe to" AKA "register" event handler.
x.PropertyChanged += HandlePropertyChanged;

// e.g. event handler...
void HandlePropertyChanged(object sender, object e)
{
    throw new NotImplementedException();
}

否则,PropertyChanged == null将是true