Advertisement
Guest User

Old vs New ViewModelBase

a guest
Aug 20th, 2015
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.94 KB | None | 0 0
  1. // old usage
  2.  public class PersonViewModel : ViewModelBase<Person>
  3.     {
  4.         private int _id;
  5.  
  6.         public int ID
  7.         {
  8.             get { return _id; }
  9.             set { Set(ref _id, value); }
  10.         }
  11. // ....
  12. public abstract class ViewModelBase<T> : INotifyPropertyChanged
  13.     {
  14.         public T Model { get; private set; }
  15.        
  16.         public event PropertyChangedEventHandler PropertyChanged;
  17.  
  18.         protected virtual bool Set<K>(ref K storage, K value, [CallerMemberName] string propertyName = null)
  19.         {
  20.             if (!object.Equals(storage, value))
  21.             {
  22.                 storage = value;
  23.                 OnPropertyChanged(propertyName);
  24.                 return true;
  25.             }
  26.  
  27.             return false;
  28.         }
  29.  
  30.         protected void OnPropertyChanged(string propertyName)
  31.         {
  32.             PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
  33.         }
  34.  
  35.         protected ViewModelBase(T model)
  36.         {
  37.             this.Model = model;
  38.         }
  39.  
  40. // NEW USAGE - workaround for passing Properties "as" reference
  41.  public class Foo : VMBase<Person>
  42.     {
  43.  
  44.         public int Age
  45.         {
  46.             get { return Model.Age; }
  47.             set { Set(value, Model, x => x.Age, "Age"); }
  48.         }
  49.  
  50.  
  51.         public Foo(Person model)
  52.             : base(model)
  53.         {
  54.         }
  55.     }
  56.  
  57. //and viewmodel base and Set method
  58.     public T Model { get; set; }
  59.         public event PropertyChangedEventHandler PropertyChanged;
  60.  
  61.         protected virtual void Set<T, I>(I input, T output, Expression<Func<T, I>> expr, [CallerMemberName] string propertyName = null)
  62.         {
  63.  
  64.             var member = (MemberExpression)expr.Body;
  65.             var prop = (PropertyInfo)member.Member;
  66.             prop.SetValue(output, input, null);
  67.             OnPropertyChanged(propertyName);
  68.         }
  69.  
  70. // WHERE T is type of model, I is type of input (property of model)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement