简体   繁体   中英

Practices for public properties in MVVM

I'm currently working alot with MVVM and since changes on the Model require triggering INotifyPropertyChanged 's OnPropertyChanged in WPF. I seek for short and nice solutions for that. My researches have shown, that an auto-property cannot trigger the OnPropertyChanged on it's own. Therefore I need to add additional fields for every Property. I got currently a ChangeProperty-Methode in my Abstract Class which helps me alot:

public abstract class PropertyExtension : INotifyPropertyChanged
{
   protected void ChangeProperty<T>(T value, ref T field, [CallerMemberName] string property = "")
        {
            if ((value!= null) && (!value.Equals(field)))
            {
                field = value;
            }
            if (property != "")
            {
                this.OnPropertyChanged(property);
            }

        }
...
}

So far this is working quite good and it saves me much time. But still I cannot use this with auto-properties. Therefore fields are still required:

  private int _ItemNumber;
    public int ItemNumber
    {
        get { return _ItemNumber; }
        set { ChangeProperty(value, ref _ItemNumber); }
    }

So the point is: when I change the Type of a property I must change the field as well. My idea was to change the field to dynamic:

    private dynamic _ItemNumber;
    public int ItemNumber
    {
        get { return _ItemNumber; }
        set { ChangeProperty(value, ref _ItemNumber); }
    }

This is working out so far and I cannot find any error. My question is: is this a good practice? Am I missing something? Is dynamic event a good choice for this? Will it affect the performance? Will it affect the memory usage? My goal is to have an easy maintainable code and for example have partial classes with only all private dynamic -fields to keep the actual model clean. Any feedback is wanted.

I suggest starting using: PropertyChanged.Fody :)

https://github.com/Fody/PropertyChanged

This way, your code is clean and tidy - as it suppose to be :)

You're theoretical MVVM model would be:

    public class ViewModel
    {
        public int ItemNumber { get; set; }
    }

Lets PropertyChanged.Fody do rest for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM