Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

wpf - How can I RaisePropertyChanged on property change?

Here I added a model to my viewmodel:

public dal.UserAccount User  {
  get
  {
    return _user;
  }
  set
  {
    _user = value;
    RaisePropertyChanged(String.Empty); 
   }
}
                

I handle property change event...

public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string propertyName)
{
  if (this.PropertyChanged != null)
    this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
        
        

This is the binding I use:

<TextBox Text="{Binding User.firstname, Mode=TwoWay, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}" />
    
    

Why the propertychange event is not triggered on updating view?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

PropertyChanged is used to notify the UI that something has been changed in the Model. Since you're changing an inner property of the User object - the User property itself is not changed and therefore the PropertyChanged event isn't raised.

Second - your Model should implement the INotifyPropertyChanged interface. - In other words make sure UserAccount implements INotifyPropertyChanged, otherwise changing the firstname will not affect the view either.

Another thing:

The parameter RaisePropertyChanged should receive is the Name of the property that has changed. So in your case:

Change:
RaisePropertyChanged(String.Empty);

To
RaisePropertyChanged("User");

From MSDN:

The PropertyChanged event can indicate all properties on the object have changed by using either null or String.Empty as the property name in the PropertyChangedEventArgs.

(No need to refresh all the Properties in this case)

You can read more on the concept of PropertyChanged here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...