【发布时间】:2010-07-15 14:01:35
【问题描述】:
好吧,这两天让我发疯了!
我是 C# 新手,并且一直通过编写一个简单的应用程序自学。
我有一个由一个组合框和两个文本框组成的简单表单。组合框包含数据库表中的实体列表。文本框允许用户添加新条目。它只是一个名称列表(名字和姓氏)。
表单上有添加、修改和删除三个按钮。
在幕后我使用数据绑定和 WPF。
好吧,我的问题是这个..
对于删除和修改操作,一切都如我所料。数据库会相应更改,并且(重要的是)组合框会立即反映对数据绑定实体所做的更改。
但是当我创建和添加一个新实体时,数据库会使用新项目进行正确更新,但是组合框不会在其列表中显示新实体(名称)。您必须退出表单并返回,才能看到组合框正确地反映了带有新添加项目的数据库表。
谁能告诉我让数据绑定控件反映其绑定到的表上的 INSERT 更改的正确做法是什么?
相关代码sn-ps如下...
private void Window_Loaded(object sender, RoutedEventArgs e)
{
this.myContext = new myEntities();
// bind the contents of the table to the combobox
myComboBox.DataContext = myContext.myPeople;
}
private void myComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
// Update the text boxes to reflect the currently selected name
this.person = myComboBox.SelectedItem as myPerson;
if (this.person != null)
{
tbFirstName.Text = this.person.Firstname;
tbSurname.Text = this.person.Surname;
}
}
//User actions...
if (userAction == crudAction.Modify)
{
// Update via the Entity Framework
person.Firstname = tbFirstName.Text;
person.Surname = tbSurname.Text;
msg = "Person details modified";
}
if (userAction == crudAction.Add)
{
person = new myPerson();
person.Firstname = tbFirstName.Text;
person.Surname = tbSurname.Text;
person.idPeople = 0; //Autoincremented db key
myContext.myPeople.AddObject(person);
msg = "New person added";
}
if (userAction == crudAction.Delete)
{
myContext.myPeople.DeleteObject(person);
msg = "Person deleted";
}
myContext.SaveChanges();
【问题讨论】:
标签: c# wpf entity-framework binding