c# - 当属性在 C# 中只有 getter 时如何创建属性更改事件

标签 c# events inotifypropertychanged propertychanged

假设我有这个类(这实际上是为了演示目的):

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/

相关文章:

c# - EF 4.3 使用本地缓存而不是从数据库中重新获取

c# - 并排装配加载问题

C# windows mobile 6 应用到 windows phone 7

python - 在 Python tkinter 中 move 更多对象

javascript - CefGlue 使用 CefDomVisitor 检测 evenfint 监听器

c# - Entity Framework - 数据库方案和测试数据的源代码控制?

java - SWT:使鼠标事件通过堆叠复合 Material 传播

wpf - 在 WPF 中将对象绑定(bind)到窗口文本框

c# - 带有枚举的 INotifyPropertyChanged

c# - INotifyPropertyChanged 更新 ontextchange