我正在尝试在singelton类中实现INotifyPropertyChanged。
这是我的代码:
public class plc:INotifyPropertyChanged {
private static plc instance; public plc() { } public static plc Instance { get { if (instance == null) { instance = new plc(); } return instance; } set { instance = value; } } private static string _plcIp{get; set;} public string plcIp { get { return _plcIp; OnPropertyChanged(); } set { _plcIp = value; } } public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged([CallerMemberName]string propertyName = null) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } }
我收到错误无法访问的代码,当然NotifyPropertyChange无法正常工作
答案 0 :(得分:3)
这是因为您在OnPropertyChanged();
之后致电return _plcIp;
。
设置值后应调用它。即:
public string plcIp
{
get
{
return _plcIp;
}
set
{
if (value != _plcIp)
{
_plcIp = value;
OnPropertyChanged();
}
}
}
在提升事件之前,您还应该检查设置器中的值是否实际发生了变化。
答案 1 :(得分:1)
您的代码中存在以下几个问题:
代码:
public class Plc : INotifyPropertyChanged {
private static Plc _instance;
private Plc() { } // constructor should be private
public static Plc Instance
{
get
{
if (_instance == null)
_instance = new Plc();
return _instance;
} // you don't need setter
}
private string _plcIp; // instance field instead of static property
public string PlcIp
{
get { return _plcIp; }
set
{
if (_plcIp == value)
return; // check if value changed
_plcIp = value; // change value
OnPropertyChanged(); // raise event
}
}
// ...
}
答案 2 :(得分:0)
这包含错误:
public string plcIp
{
get
{
return _plcIp;
OnPropertyChanged(); //This row..
}
set { _plcIp = value; }
}
在Set方法中,您希望在UI中进行更新,而不是在获得值时。 像这样:
public string plcIp
{
get { return _plcIp; }
set { _plcIp = value; OnPropertyChanged(); }
}