我正在尝试将一个人添加到露营者(人)列表中。我已将ListView(GridView)
绑定到数据库,它显示所有名称,年龄和成绩。但现在我正在尝试添加一个新人并将其与其他人一起添加(显示)到ListView
。任何帮助是极大的赞赏。
以下是我的内容:ObservableCollection
class BindingCamper
{ // This class assist in binding campers from listview to the textboxes on the camperspage
public ObservableCollection<Camper> Campers { get; private set; }
public BindingCamper()
{
Campers = new ObservableCollection<Camper>();
}
}
这是我在列表视图中添加名称列表的地方:
MainWindow _parentForm;
public ObservableCollection<Camper> Campers { get; private set; }
public CampersPage(MainWindow parent)
{
_parentForm = parent;
InitializeComponent();
var bindMe = new BindingCamper();
for (int i = 0; i < _parentForm.allCampers.Count; i++)
bindMe.Campers.Add(new Camper { Name = "" + _parentForm.allCampers[i].getName(), Ages = _parentForm.allCampers[i].getAge(), SchoolGrade = _parentForm.allCampers[i].getGrade() });
DataContext = bindMe;
这是我添加新露营者(人)的地方,我正在尝试将他/她添加到列表视图中:
String nameMe;
nameMe = txtNewFirstName.Text ;
int age;
int grade;
if (nameMe != "" && IsNumber(txtNewGrade.Text) && IsNumber(txtNewAge.Text))
{
age = Convert.ToInt16(txtNewAge.Text);
grade = Convert.ToInt16(txtNewGrade.Text);
// Create New Camper
Camper person = new Camper(age, grade, nameMe);
_parentForm.allCampers.Add(person);
//_parentForm.camperPage.listViewCampers.Items.Refresh();
var bind = new BindingCamper();
// bind.Campers.Add(new Camper { Name = person.getName(), Ages = person.getAge(), SchoolGrade = person.getGrade() });
// _parentForm.camperPage.Campers.Add(new Camper { Name = person.getName(), Ages = person.getAge(), SchoolGrade = person.getGrade() });
Close();
答案 0 :(得分:0)
您不应刷新数据库以添加露营车:
Camper person = new Camper(age, grade, nameMe);
if TryAddToDatabase(person)
{
bindMe.Campers.Add(person);
}
如果ListView
绑定到bindMe.Campers,它将自动刷新并显示新项目。我还建议您完全阅读WPFTutorial,以便将来不再做任何额外的工作。