如何在 C# 中 属性 只有 getter 时创建 属性 更改事件
How to create a property changed event when the property has only a getter in C#
假设我有这个 class(这实际上是为了演示目的):
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
接口,但我需要 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;
}
假设我有这个 class(这实际上是为了演示目的):
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
接口,但我需要 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;
}