NotifyPropertyChanged的基本例程

时间:2018-03-11 18:40:41

标签: c# wpf mvvm

所以我说我上课了:

SurfaceLoad.cs

public class SurfaceLoad : Load
{
    private double force;
    public double Force{ get => force; set{force = value;}}

    public SurfaceLoad(double f){
        Force = f;
    }
    public SurfaceLoad(){
        Force = 0.0;
    }
}

我有我的ViewModel:

SurfaceLoadViewModel.cs

public class SurfaceLoadViewModel{

   private SurfaceLoad surfaceLoad = new SurfaceLoad();

   public double Force{
        get => surfaceLoad.Force;
        set{
            surfaceLoad.Force = value;
            NotifyPropertChanged("Force");
        } 
   } 

   public SurfaceLoadViewModel(){
   }
}

正如我已经发现的那样,我必须以一种良好的MVVM方式将SurfaceLoad成员的所有访问器放入ViewModel中,因为Model本身不应包含任何交互逻辑。

问题:

现在我有多个Load实现(SurfaceLoad,PointLoad,AreaLoad,...)。所有这些都是名为LoadContainer的类的成员,它仅用于管理同时发生的负载包。

如何有效管理ViewModel中的所有类型?我是否必须围绕每个值包装一个属性?

2 个答案:

答案 0 :(得分:1)

您需要在SurfaceLoad类中实现INotifyPropertyChanged接口。

    public class SurfaceLoad : Load, INotifyPropertyChanged
    {
        private double force;
        public double Force
        {
            get { return force; }
            set
            {
                force = value;
                NotifyPropertyChanged("Force");
            }
        }
        public SurfaceLoad(double f)
        {
            Force = f;
        }
        public SurfaceLoad()
        {
            Force = 0.0;
        }
        public event PropertyChangedEventHandler PropertyChanged;
        protected void NotifyPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = this.PropertyChanged;
            if (handler != null)
            {
                var e = new PropertyChangedEventArgs(propertyName);
                handler(this, e);
            }
        }
        protected void NotifyPropertyChanged<T>(Expression<Func<T>> propertySelector)
        {
            var propertyChanged = PropertyChanged;
            if (propertyChanged != null)
            {
                string propertyName = GetPropertyName(propertySelector);
                propertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }

答案 1 :(得分:0)

前两条评论对我帮助很大。 此外,我做了一些研究并得出结论,将“NotifyPropertyChanged”处理程序写入模型更有效,因为这个程序对mvvm原则不起作用!