如何遍历列表中对象的属性?

时间:2016-12-03 08:03:27

标签: c#

我有一个对象列表,我想使用' previous'来迭代对象的属性。和' next' WPF中的按钮。
例如,如果我遍历对象的属性,则单击“之前的”对象。按钮我遇到位于我当前正在迭代的对象之前的对象的属性以及' next'按钮......

如果我有一个Student类,其中包含存储在studentList中的属性的名字和姓氏以及学生对象的数量,那我该怎么做?
我只关心' next'的eventHandler方法的实现。和之前的'按钮

class Student
{
    private string firstName;

    public string FirstName
    {
        get { return firstName; }
        set { firstName = value; }
    }
    private string lastName;

    public string LastName
    {
        get { return lastName; }
        set { lastName = value; }
    }
    private string city;

    public string City
    {
        get { return city; }
        set { city = value; }
    }

}

private void btnCreateStudent_Click(object sender, RoutedEventArgs e)
    {
        Student student1 = new Student();
        student1.FirstName = txtFirstName.Text;
        student1.LastName = txtLastName.Text;
        student1.City = txtCity.Text;

        studentList.Add(student1);

        MessageBox.Show("Student Created");

        txtFirstName.Clear();
        txtLastName.Clear();
        txtCity.Clear();
    }

private void btnPrevious_Click(object sender, RoutedEventArgs e)
    {
      // need implementation code
    }
private void btnNext_Click(object sender, RoutedEventArgs e)
    {
      // need implementation code
    }

由于

1 个答案:

答案 0 :(得分:0)

假设您没有使用任何绑定内容,您应该编写一个帮助方法,使用当前选定的Student对象中的值填充UI:

private void bindStudent(Student student) {
    if (student != null) {
        txtFirstName.Text = student.FirstName;
        txtLastName.Text = student.LastName;
        txtCity.Text = student.City;
    }
    else { // Just a fail-safe.
        txtFirstName.Clear();
        txtLastName.Clear();
        txtCity.Clear();
    }
}

然后,您的“下一个”和“上一个”按钮只需要从studentList中获取相应的对象,然后使用它调用该方法。您需要做的一件事是记住当前选择列表中的哪个对象以获取“下一个”和“上一个”对象。

private int curSelectionIndex = -1;

private void btnPrevious_Click(object sender, RoutedEventArgs e)
{
  if (curSelectionIndex - 1 >= 0)
  {
      curSelectionIndex--;
      bindStudent(studentList[curSelectionIndex]);
  }
}

private void btnNext_Click(object sender, RoutedEventArgs e)
{
  if (curSelectionIndex + 1 < studentList.Count)
  {
      curSelectionIndex++;
      bindStudent(studentList[curSelectionIndex]);
  }
}

您的问题没有说明在创建新学生后您想要使用UI做什么,所以我没有做任何关于更新该选择的事情。