ObservableCollection能通知他变化了也正是因为它实现了INotifyPropertyChanged接口,
在wpf项目中经常会遇到把List<T>转换为ObservableCollection<T>.
总结了一下几种方法:
首先有个 Employee实体类:
public class Employee
{
private string name; public string Name
{
get { return name; }
set { name = value; }
} private int age; public int Age
{
get { return age; }
set { age = value; }
} private string sex; public string Sex
{
get { return sex; }
set { sex = value; }
}
接着有一个返回值为List<Employee>类型的方法:
/// <summary>
/// 填充一个List<Employee>
/// </summary>
/// <returns></returns>
public List<Employee> GetEmployeeList()
{
List<Employee> list = new List<Employee>
{
new Employee{Name="张三",Age=,Sex="男"},
new Employee{Name="李四",Age=,Sex="男"},
new Employee{Name="小红",Age=,Sex="女"},
};
return list;
}
有一个只读的ObservableCollection<Employee>类型的属性:
private ObservableCollection<Employee> employeeList; public ObservableCollection<Employee> EmployeeList
{
get
{
if (employeeList == null)
{
employeeList = new ObservableCollection<Employee>();
}
return employeeList;
}
}
集合类型属性设置为只读的好处这里不展开。
最后是调用GetEmployeeList方法获得一个List<Employee>的list,把这个list赋值给ObservableCollection<Employee>类型的集合属性:
List<Employee> list = GetEmployeeList();
if (list != null)
{
EmployeeList.Clear();
//方法一如果ObservableCollection集合是可读可写的(set)
//EmployeeList = new ObservableCollection<Employee>(list); //错误:无法对属性或索引器“EmployeeList”赋值 -- 它是只读的
//方法二:遍历list添加到ObservableCollection集合
//foreach (Employee item in list)
//{
// EmployeeList.Add(item);
//}
//方法三:方法二的简写
list.ForEach(p => EmployeeList.Add(p)); //遍历list添加到EmployeeList中
}