【发布时间】:2012-04-04 01:55:56
【问题描述】:
我想将列表视图数据上下文设置为等于可观察集合,以便对集合的更改可以反映在我的列表视图上。我将 observable 集合创建为:
public static ObservableCollection<T> ToObservableCollection<T>(IEnumerable<T> enumeration)
{
return new ObservableCollection<T>(enumeration);
}
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
Entities.DatabaseModel m = new Entities.DatabaseModel();
var q = from t in m.TimeSheet
join emp in m.Employees on t.idEmployee equals emp.id
where emp.id == CurrentEmploye.id
select new
{
firstName = emp.firstName,
lastName = emp.lastName,
position = emp.position,
clockInDate = t.clockInDate,
clockOutDate = t.clockOutDate,
};
// here I create the observablecollection!!!!!!!!!!!!!!
listView1.DataContext = ToObservableCollection(q);
}
现在我的问题是,如果我想向 ObservableCollection 添加项目,我该怎么做?如果我这样做 listView1.DataContext.Add( 这将导致错误。
也就是说我有方法
private void btnClockIn_Click(object sender, RoutedEventArgs e)
{
// I will like to add items to the observable collection in here
这是我尝试过的,但它不起作用:
dynamic collection;
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
// CurrentEmploye some employee
Entities.DatabaseModel m = new Entities.DatabaseModel();
var q = from t in m.TimeSheet
join emp in m.Employees on t.idEmployee equals emp.id
where emp.id == CurrentEmploye.id
select new
{
firstName = emp.firstName,
lastName = emp.lastName,
position = emp.position,
clockInDate = t.clockInDate,
clockOutDate = t.clockOutDate,
};
collection = ToObservableCollection(q);
}
private void btnClockIn_Click(object sender, RoutedEventArgs e)
{
collection.Add(new
{
firstName = "Antonio",
lastName = "Nam",
position = "Amin",
clockInDate = DateTime.Now,
clockOutDate = DateTime.Now
});
【问题讨论】:
-
你绝对需要这个匿名类型吗?查询是否会返回与您指定的字段不同的字段?
-
你说得对,我只是想节省时间,因为我在其他地方需要此功能,但我可能最终浪费了更多时间..
-
您有一些选择,使用命名类型是最快的。我会发布一个更详细的答案。
标签: c# observablecollection datacontext