添加到绑定的ListView

本文关键字:ListView 绑定 添加 | 更新日期: 2023-09-27 18:10:50

我正在尝试将一个人添加到露营者(人)列表中。我已经将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>();
    } 
}

下面是我在listview中添加名字列表的地方:

       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;

我在这里添加了一个新的露营者(人),我试图将他/她添加到listview:

            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();

添加到绑定的ListView

您不应该刷新数据库来添加camper:

Camper person = new Camper(age, grade, nameMe);
if TryAddToDatabase(person)
{
    bindMe.Campers.Add(person);
}

如果ListView被绑定到bindMe。它会自动刷新并显示新项目。我还建议您完全阅读WPFTutorial,这样您以后就不会做任何额外的工作了。