开发者

Adding to a bound ListView

开发者 https://www.devze.com 2023-04-11 21:59 出处:网络
I\'m trying to add a person to a list of campers(people). I have bound the ListView(GridView) to the database and it displays all the names, ages, and grades. But now I\'m trying to add a new person a

I'm trying to add a person to a list of campers(people). I have bound the ListView(GridView) to the database and it displays all the names, ages, and grades. But now I'm trying to add a new person and add(display) him to the ListView along with everyone else. Any help is greatly appreciated.

Here's what I have: 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>();

    } 
}

Here is where I add the list of names to the 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].getGr开发者_Python百科ade() });
        DataContext = bindMe;

Here is where I add a new camper(person) and I'm trying to add him/her to the 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();


You shouldn't refresh the database to add camper:

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

If ListView is bounded to bindMe.Campers it would refresh automatically and show new item. I also would recommend you completely read the WPFTutorial so you won't do any extra work in the future.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号