How to avoid implementing INotifyPropertyChanged manually

后端 未结 7 1685
名媛妹妹
名媛妹妹 2021-01-05 02:44

Is there some way to avoid this. I have a lot of classes that are bound to DataGridViews and they are just simple collection of properties with default getter and setter. So

相关标签:
7条回答
  • 2021-01-05 03:22

    Here is a similar solution to Marc, that has been extended to allow multiple property onpropertychanges and multiple RaiseCanExecuteChanged

    simplest example usage

    string _firstName;
    public string FirstName
    {
        get { return _firstName; }
        set { OnPropertyChanged(ref _firstName, value, "FirstName"); }
    }
    

    advanced example using multiple property updates and multiple commands

    string _firstName;
    public string FirstName
    {
        get { return _firstName; }
        set { OnPropertyChanged(ref _firstName, value, "FirstName", "FullName", Command1, Command2); }
    }
    

    The advanced example calls OnProperty changed on firstname and fullname and also calls RaiseCanExecuteChanged for command1 and command2

    base ViewModel code

    protected void OnPropertyChanged<T>(ref T field, T value, params object[] updateThese)
    {
        if (!EqualityComparer<T>.Default.Equals(field, value))
        {
            field = value;
            OnPropertyChanged(updateThese);
        }
    }
    
    protected void OnPropertyChanged(params object[] updateThese)
    {
        if (PropertyChanged != null)
        {
            foreach (string property in updateThese.Where(property => property is string))
                PropertyChanged(this, new PropertyChangedEventArgs(property));
    
            foreach (DelegateCommand<object> command in updateThese.Where(property => property is DelegateCommand<object>))
                command.RaiseCanExecuteChanged();
        }
    }
    
    0 讨论(0)
提交回复
热议问题