Trying to understand INotifyPropertyChanged

后端 未结 4 1945
清歌不尽
清歌不尽 2021-01-25 04:25

Several (newbie) questions:

1) I see a lot of

public Person SelectedPerson { get; set; } 

I am assuming this does NOT fire a property

相关标签:
4条回答
  • 2021-01-25 04:32

    Yes, Auto Properties do not fire the PropertyChanged event.

    You can get the CanDeletePerson to re-evaluate by adding OnPropertyChanged("CanDeletePerson") to the SelectedPerson setter.

    I'm not sure if your last bit is a question, but you can subscribe to the PropertyChanged event like any other event. MyClass.PropertyChanged += MyClassPropertyChanged

    Where MyClassPropertyChanged is

    private void MyClassPropertyChanged(object sender, PropertyChangedEventArgs args)
    {
        args.PropertyName .... //<-- Name of property changed.
    }
    

    But you shouldn't need to. WPF does the subscribing to the event that it needs to.

    0 讨论(0)
  • 2021-01-25 04:38
    1. Correct - that does not fire
    2. Yes, to have CanDeletePerson reevaluated, you can raise PropertyChanged on CanDeletePerson, like so

          set
          { 
              if ((this.selectedPerson != value))
              { 
                  this.selectedPerson = value; 
                  base.OnPropertyChanged("SelectedPerson"); 
                  base.OnPropertyChanged("CanDeletePerson");
              }
          }
      
    3. Like any normal event, but if you're using WPF, you typically don't need to subscribe explicitly

    0 讨论(0)
  • 2021-01-25 04:39

    Here's a link to a good article introducing the MVVM pattern.

    Specifically, if you look at the RelayCommand class, it does a nice job of implementing an ICommand object and allowing you to specify a predicate to evaluate whether or not the Command may be executed.

    The evaluation of the canExecute predicate in the RelayCommand saves you from binding a separate property to the IsEnabled property of the Button.

    I typically follow the example in the article of implementing a private property which supplies the Boolean value for the canExecute predicate.

    That article was a good help to me to get started with the pattern.

    0 讨论(0)
  • 2021-01-25 04:47

    If you use the PropertyChanged event, your class needs to implements the INotifyProperyChanged interface and raise the event where necessary. In WPF, the default for the databinding is the DependencyProperty, so if you work with the PropertyChanged event, you must do something into the XAML (Assuming that your class person have a Name property where you raise the PropertyChanged event):

    <TextBlock Text={Binding Path=Name, UpdateSourceTrigger=PropertyChanged} />
    
    0 讨论(0)
提交回复
热议问题