INotifyPropertyChanged WPF

What is the purpose of INotifyPropertyChanged. I know that this event is fired whenever the property changes, but how can View / UI know 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 user interface that the property has changed. For example, when a user assigns a blank or empty name to the first name, how can I display a MessageBox in the user interface.

+3
source share
3 answers

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

Kind just signed up for an event that tells him everything he needs. The event includes the name of the changed property, therefore, if the user interface element is bound to this property, it is updated.

+5
source

WPF can know, because it can check whether this object implements this interface, then drops the object on the specified interface and logs the event. He can then initiate a binding infrastructure to update the display. If you also want to respond, you can register to participate in the same event.

+3
source

EDIT: I am re-reading your question and some of your comments. Here is a possible solution using the DataContextChanged event and the INotifyPropertyChanged interface on your Customer object. You should also learn Data Binding Verification in WPF and .Net 3.5.

 <TextBox Text="{Binding FirstName}" /> // assuming: // myWindow.DataContext = new Customer(); myWindow.DataContextChanged += MyWindow_DataContextChanged; private void MyWindow_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e) { var oldCustomer = e.OldValue as Customer; if (oldCustomer != null) { oldCustomer.PropertyChanged -= Customer_CheckProps; } var newCustomer = e.NewValue as Customer; if (newCustomer != null) { newCustomer.PropertyChanged += Customer_CheckProps; } } private void Customer_CheckProps(object sender, PropertyChangedEventArgs e) { var customer = sender as Customer; if (customer != null) { if (e.PropertyName == "FirstName" && String.IsNullOrEmpty(customer.FirstName)) { // Display Message Box } } } 
+3
source

Source: https://habr.com/ru/post/895791/


All Articles