Databindings don't seem to refresh

前端 未结 1 967
走了就别回头了
走了就别回头了 2020-11-27 08:15

For some reason I\'m really struggling with this. I\'m new to wpf and I can\'t seem to find the information I need to understand this simple problem.

I am trying to

相关标签:
1条回答
  • 2020-11-27 08:46

    Implement INotifyPropertyChanged on your class. If you have many classes that need this interface, I often find it helpful to use a base class like the following.

    public abstract class ObservableObject : INotifyPropertyChanged
    {
    
        protected ObservableObject( )
        {
        }
    
        public event PropertyChangedEventHandler PropertyChanged;
    
        protected virtual void OnPropertyChanged( PropertyChangedEventArgs e )
        {
            var handler = PropertyChanged;
            if ( handler != null ) {
                handler( this, e );
            }
        }
    
        protected void OnPropertyChanged( string propertyName )
        {
            OnPropertyChanged( new PropertyChangedEventArgs( propertyName ) );
        }
    
    }
    

    Then you just have to make sure you raise the PropertyChanged event whenever a property value changes. For example:

    public class Person : ObservableObject {
    
        private string name;
    
        public string Name {
            get {
                  return name;
            }
            set {
                  if ( value != name ) {
                      name = value;
                      OnPropertyChanged("Name");
                  }
            }
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题