using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication3
{
class Cls : INotifyPropertyChanged
{
private string my;
public string MyProperty
{
get
{
return my;
}
set
{
my = value;
PropertyChanged(this, new PropertyChangedEventArgs("MyProperty"));
}
}
public Cls()
{
MyProperty = "Hello";
}
public void print()
{
Console.WriteLine(MyProperty);
}
protected virtual void OnPropertyChanged(string name)
{
}
public event PropertyChangedEventHandler PropertyChanged;
}
class Program
{
static void Main(string[] args)
{
Cls s = new Cls();
s.print();
}
}
}
当我运行此代码时,它给出:
当我不使用
INotifyPropertyChanged
时它工作正常。我不明白问题的原因。 最佳答案
没有人在听 PropertyChanged
,当尝试调用它时它将为空。改用 OnPropertyChanged
方法:
private void OnPropertyChanged(string propertyName){
var handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
// With C# 6 this can be replaced with
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public string MyProperty
{
get { return my; }
set
{
if (my == value)
return;
my = value;
OnPropertyChanged("MyProperty");
}
}
为了避免它成为
null
你必须订阅它,例如从你的 main 方法:static void Main(string[] args){
Cls s = new Cls();
s.PropertyChanged += (sender, args) => MessageBox.Show("MyProperty changed!");
s.print();
}
这是一种奇特的写作方式
static void Main(string[] args){
Cls s = new Cls();
s.PropertyChanged += ShowMessage;
s.print();
}
private void ShowMessage(object sender, PropertyChangedEventArgs args){
MessageBox.Show("MyProperty changed!");
}
什么对你来说更清楚。
您可以阅读有关事件的更多信息 here
关于c# - 将值设置为属性时出现 NullReferenceException,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21833769/