简体   繁体   English

MVVM中的公共属性实践

[英]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. 我目前正在大量使用MVVM,并且由于对模型的更改需要在WPF中触发INotifyPropertyChangedOnPropertyChanged 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. 我的研究表明,自动属性无法OnPropertyChanged触发OnPropertyChanged Therefore I need to add additional fields for every Property. 因此,我需要为每个属性添加其他字段。 I got currently a ChangeProperty-Methode in my Abstract Class which helps me alot: 我的抽象类中目前有一个ChangeProperty-Methode,它可以帮助我很多:

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. 我的目标是拥有一个易于维护的代码,例如,只具有所有private dynamic字段的部分类,以保持实际模型的整洁。 Any feedback is wanted. 需要任何反馈。

I suggest starting using: PropertyChanged.Fody :) 我建议开始使用:PropertyChanged.Fody :)

https://github.com/Fody/PropertyChanged 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: 您的理论MVVM模型将是:

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

Lets PropertyChanged.Fody do rest for you. 让PropertyChanged.Fody替您休息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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