我想將listview datacontext設置爲等於可觀察集合,以便對集合所做的更改可能反映在我的列表視圖上。我創建的可觀察集合如下:make或declare ObservableCollection <a>變量全局其中a =匿名類型
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
});
你絕對需要這是一個匿名類型?查詢是否會返回與您指定的字段不同的字段? – 2012-04-02 23:49:36
你是對的我只是想節省時間,因爲我需要在其他一些地方的功能,但我可能最終浪費更多的時間.. – 2012-04-03 01:23:03
你有一些選擇,使用命名類型只是最快。我會發布更多細節的答案。 – 2012-04-03 01:30:19