我将一个可观察的集合(FoodList)绑定到我的WinForm中的BindingSource。此BindingSource由表单上的数据网格使用。我假设当我向集合中添加一个新项目时,它会引发一个事件,并且我的网格中会出现一个新行。但这不会发生。
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();
}
}
}