问题
I am binding an observable collection (FoodList) to a BindingSource in my WinForm. This BindingSource is used by a datagrid on the form. I had assumed that when I added a new item to the collection it would raise an event and a new row would show up in my grid. This does not happen though.
namespace Foods
{
public class FoodList : ObservableCollection<Food>
{
}
}
private void frmFoods_Load(object sender, EventArgs e)
{
try
{
foodSource = new Source("Foods.xml");
foodBindingSource.DataSource = foodSource.Foods;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void AddFood()
{
using (frmFood frm = new frmFood())
{
frm.ShowDialog(this);
if (!frm.Canceled)
{
foodSource.Foods.Add(frm.Food); // <-- No new row.
//foodBindingSource.ResetBindings(false);
foodDataGridView.ClearSelection();
foodDataGridView.CurrentCell = foodDataGridView[0, foodDataGridView.Rows.Count - 1];
foodDataGridView.Focus();
}
}
}
回答1:
ObservableCollection<T>
doesn't work with WinForms controls.
However BindingList<T> will work the way you expect.
来源:https://stackoverflow.com/questions/12015576/binding-observablecollection-to-datagridview