假设我有这个类(这实际上是为了演示目的):
class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string IdNumber { get; set; }
// CheckPopulationRegistry() checks against the database if a person
// these exact properties (FirstName, LastName, IdNumber etc.) exists.
public bool IsRealPerson => CheckPopulationRegistry(this);
}
我想在 IsRealPerson
更改时收到通知。
通常,我会实现 INotifyPropertyChanged
接口(interface),但之后我需要 create an OnIsRealPersonChanged()
method, and call it from the setter ,我没有。
想法?
最佳答案
你需要这样的东西:
public class Person : INotifyPropertyChanged
{
private string firstName;
private string lastName;
private void OnPropertyChanged([CallerMemberName]string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
private bool CheckPopulationRegistry(Person p)
{
// TODO:
return false;
}
public string FirstName
{
get { return firstName; }
set
{
if (firstName != value)
{
firstName = value;
OnPropertyChanged();
OnPropertyChanged(nameof(IsRealPerson));
}
}
}
public string LastName
{
get { return lastName; }
set
{
if (lastName != value)
{
lastName = value;
OnPropertyChanged();
OnPropertyChanged(nameof(IsRealPerson));
}
}
}
// IdNumber is omitted
public bool IsRealPerson => CheckPopulationRegistry(this);
public event PropertyChangedEventHandler PropertyChanged;
}
关于c# - 当属性在 C# 中只有 getter 时如何创建属性更改事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40280786/