Can or cannot Notifypropertychanged exist in the public properties of a Model?

Asked

Viewed 22 times

0

Hi, I’m creating an App with the MVVM standard but some related issues I’m not able to clarify on the subject, I’ll leave the App link here If anyone wants to see to point out some possible mistake or even if they want to use it for study purposes, feel free.

Notifypropertychanged can or can’t exist in the public properties of a Model?

If so, can you tell me when or for what situation this Notifypropertychanged would be used in Model? Can describe in situations not necessarily in code (although it is better).

Thanks.

1 answer

0


Hello, @MATCH.

If you are referring to the interface INotifyPropertyChanged, this is a contract to ensure data change timing between View and Viewmodel(in this case does not enter the model).

When Viewmodel has some altered properties, it must invoke the event PropertyChangedEventHandler informing which property has changed through the argument PropertyChangedEventArgs

To answer your question: Notifypropertychanged may or may not exist in the public properties of a Model?

The answer is: It depends, because syntactically you would be breaking the principles of Design Pattern MVVM that says that only Viewmodel should communicate with the View, but nothing stops you from doing it, it will work the same way, as long as your Viewmodel is mapped to some Model property.

Base class for Common use among Viewmodels

public class BaseViewModel : INotifyPropertyChanged 
{
        /// <summary>
        /// Occurs when a property value changes.
        /// </summary>
        public event PropertyChangedEventHandler PropertyChanged;


        /// <summary>
        /// Raises this object's PropertyChanged event.
        /// </summary>
        /// <param name="propertyName">Name of the property used to notify listeners. 
        /// that support <see cref="CallerMemberNameAttribute"/>.</param>
        protected void RaisePropertyChanged([CallerMemberName]string propertyName = null)
        {
            OnPropertyChanged(propertyName);
        }
}

Example of Use

public class MinhaViewModel : BaseViewModel 
{
   private string _minhaString;
   public string MinhaString
   {
     get => _minhaString;
     set
     {
       if(value == _minhaString) return;

       _minhaString = value;
       RaisePropertyChanged()
     }
   }
}

Now MinhaString can be used in View problems.

  • I understood Vinicius was very clear, thank you for the reply and the example.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.