I want to set the listview datacontext equal to an observable collection so that changes to the collection may reflect on my listview. I create the observable collection as:
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);
}
now my problem is that if I want to add items to the ObservableCollection how can I do that? If I do listView1.DataContext.Add( that will result on an error.
In other words I have the method
private void btnClockIn_Click(object sender, RoutedEventArgs e)
{
// I will like to add items to the observable collection in here
This is what I have tried and it does not work:
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
});