我遇到問題,如下所述。我是新來的.NET/Visual Studio(2013),我想弄清楚爲什麼下面的代碼不會工作。事件處理 - Visual Studio
我有下面的類
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調用它。
然後SaveProperty方法被稱爲從其他類這樣的:
PropertySettings.Instance.SaveProperty("Width", Width);
我遇到的問題是,的PropertyChanged總是空,因此PropertyChanged事件不會被調用。
你在哪裏連接PropertyChanged事件處理程序? –
什麼都訂閱了'PropertyChanged'?它不會有價值,除非它至少有一個用戶。 – lintmouse
水晶球說,你應該使這個類的構造函數*私人*。現在編譯器會告訴你你做錯了什麼。 –