ObservableCollection首先它是一个集合,但它是一个既实现了INotifyPropertyChanged接口又实现了INotifyCollectionChanged接口的集合,这是它与List<T>的不同之处。
使用ObservableCollection<T>注定要比List<T>消耗性能,所以我一直在探寻它们各自不同的使用场合。而且,当泛型参数T也实现了INotifyPropertyChanged接口时,就更加复杂了。
使用这个动态集合能很好的更新UI界面,但是它对LINQ的支持不友好,所以还是改用List<T>集合。
对象实体T实现接口INotifyPropertyChanged接口口,属性都要被监听,这样的当对象的属性改变,就会通知xaml界面刷新。另外viewmodel 也要实现的INotifyPropertyChanged,List<T>集合属性也设置监听。
例子:
public class HuBanModel : INotifyPropertyChanged{
public event PropertyChangedEventHandler PropertyChanged;
internal void NotifyPropertyChange(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); }
private string _ceBanType;
public string CeBanType
{
get { return _ceBanType; }
set
{
_ceBanType = value;
NotifyPropertyChange("CeBanType");
}
}
}
public class CeBanEditViewModel : INotifyPropertyChanged{
private List<HuBanModel> _leftHuBans;
public List<HuBanModel> LeftHuBans
{
get { return _leftHuBans; }
set
{
_leftHuBans = value;
OnPropertyChanged("LeftHuBans");
}
}
}
public List<HuBanModel> RemoveList(List<HuBanModel> hubanList, int index)
{
List<HuBanModel> Newhubanlist = new List<HuBanModel>();
hubanList.RemoveAt(index);
int length = hubanList.Count;
for (int i = 0; i < length; i++)
{
Newhubanlist.Add(hubanList[i]);
}
return Newhubanlist;
}
public void Remove(bool isleftCeBan, int index)
{
if (isleftCeBan)
{
this.LeftHuBans = RemoveList(this.LeftHuBans, index);
}
else
{
this.RightHuBans = RemoveList(this.RightHuBans, index);
}
}
this.LeftHuBans = 要重新New 一个List对象,使引用地址发生改变,这样就能出发notif机制,通知UI更新界面。