INotifyPropertyChanged + ObservableCollection 提供通知,客户端实时刷新
INotifyPropertyChanged 通知客户端属性值已更改。
ObservableCollection 表示一个动态数据集合,可在添加、删除项目时提供通知,使UI更新。
修改属性时更新,需要实体类继承NotifyPropertyChanged,使指定的属性提供通知机制。
ObservableCollection<DemoDto> _DataList;
public class DemoDto : NotifyPropertyChangedEx
{
public string Guid { get; set; }
private bool _bChecked;
public bool IsChecked
{
get => _bChecked;
set => UpdateProperty(ref _bChecked, value);
}
private int _otherProperty;
public int OtherProperty { get { return _otherProperty; } set { UpdateProperty(ref _otherProperty, value); } }
public ObservableCollection<DemoDetail> InfoDetails { get; set; }
}
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
public class NotifyPropertyChangedEx : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([System.Runtime.CompilerServices.CallerMemberName] string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public void UpdateProperty<T>(ref T propertyValue, T newValue, [System.Runtime.CompilerServices.CallerMemberName]string propertyName = "")
{
if (Equals(propertyValue, newValue))
{
return;
}
propertyValue = newValue;
OnPropertyChanged(propertyName);
}
}
或者
/// <summary>
/// 对象扩展
/// </summary>
public class DemoDtoEx : DemoDto, INotifyPropertyChanged
{
private bool _bChecked;
public bool IsChecked
{
get => _bChecked;
set => UpdateProperty(ref _bChecked, value);
}
string _name;
/// <summary>
/// 名称
/// </summary>
public new string Name
{
get => _Name;
set => UpdateProperty(ref _name, value);
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([System.Runtime.CompilerServices.CallerMemberName] string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public void UpdateProperty<T>(ref T propertyValue, T newValue, [System.Runtime.CompilerServices.CallerMemberName] string propertyName = "")
{
if (Equals(propertyValue, newValue))
{
return;
}
propertyValue = newValue;
OnPropertyChanged(propertyName);
}
}
ObservableCollection与List互相转换
List<DemoDto> data = _DataList.ToList()
_DataList = new ObservableCollection<DemoDto>(data);