public class User : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private uint _userId;
private string _name;
public uint UserId
{
get => _userId;
set {
if(_userId == value)
return;
_userId = value;
this.OnPropertyChanged("UserId"); // 传统写法
}
}
public string Name
{
get => _name;
set {
if(_name == value)
return;
_name = value;
this.OnPropertyChanged(nameof(Name)); // nameof 为 C# 7.0 新增操作符
}
}
protected virtual void OnPropertyChanged(string propertyName)
{
// 注意 ?. 为 C# 7.0 新增操作符
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class User : ModelBase
{
private uint _userId;
private string _name;
public uint UserId
{
get => _userId;
set => this.SetPropertyValue(nameof(UserId), ref _userId, value);
}
public string Name
{
get => _name;
set => this.SetPropertyValue(nameof(Name), ref _name, value);
}
}
public class User : ModelBase
{
public uint UserId
{
get => (uint)this.GetPropertyValue(nameof(UserId));
set => this.SetPropertyValue(nameof(UserId), value);
}
}
public class User : ModelBase
{
public uint UserId
{
get => (uint)this.GetPropertyValue();
set => this.SetPropertyValue(value);
}
}
public class User : ModelBase
{
public uint UserId
{
get => this.GetPropertyValue(() => this.UserId);
set => this.SetPropertyValue(() => this.UserId, value);
}
}
using System;
using System.Linq.Expressions;
public class ModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected object GetPropertyValue([CallerMemberName]string propertyName = null);
protected T GetPropertyValue<T>(Expression<Func<T>> property);
protected void SetPropertyValue<T>(string propertyName, ref T field, T value);
protected void SetPropertyValue<T>(string propertyName, T value);
protected void SetPropertyValue<T>(Expression<Func<T>> property, T value);
}
public class ModelBase : INotifyPropertyChanged
{
// other members
public bool HasChanges(params string[] propertyNames);
public IDictionary<string, object> GetChangedPropertys();
}