Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

INotifyPropertyChanged WPF

What is the purpose of INotifyPropertyChanged. I know this event is fired whenever a property is changed but how can the View/UI knows that this event is fired:

Here is my Customer class that implements the INotifyPropertyChanged event:

public class Customer : INotifyPropertyChanged
    {
        private string _firstName;

        public string LastName { get; set; }

        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged(string propertyName)
        {
            if(PropertyChanged != null)
                PropertyChanged(this,new PropertyChangedEventArgs(propertyName));

        }

        public string FirstName
        {
            get { return _firstName; }

            set
            {
                _firstName = value;
                OnPropertyChanged("FirstName");
            }
        }
    }

But now how to notify the UI that property has changed. Like when the user assigns null or empty to the first name how can I display a MessageBox on the UI.


1 Answers

INotifyPropertyChanged allows WPF UI elements (via the standard data binding mechanisms) to subscribe to the PropertyChanged event and automatically update themselves. For example, if you had a TextBlock displaying your FirstName property, by using INotifyPropertyChanged, you can display it on a form, and it will automatically stay up to date when the FirstName property is changed in code.

The View just subscribes to the event - which tells it everything necessary. The event includes the name of the changed property, so if a UI element is bound to that property, it updates.

like image 59
Reed Copsey Avatar answered Aug 11 '26 08:08

Reed Copsey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!