c#:在WPF中通过按钮访问下一个或上一个元素

本文关键字:下一个 访问 上一个 元素 按钮 WPF | 更新日期: 2023-09-27 18:01:24

我有一个项目,该项目使用按钮访问泛型集合中的下一个或上一个元素学生类有3个属性:字符串姓、名和城市。有人能帮我实现吗?我认为它可能与IEnumerator()有关,但我卡住了

public partial class MainWindow : Window
{
    List<Student> Students = new List<Student>();
    public MainWindow()
    {
        InitializeComponent();

        txtFirstName.Clear();
        txtLastName.Clear();
        txtCity.Clear();
    }
    private void btnCreateStudent_Click(object sender, RoutedEventArgs e)
    {
        Student stu = new Student();
        stu.Firstname = txtFirstName.Text;
        stu.Lastname = txtLastName.Text;
        stu.City = txtCity.Text;
        //List<Student> Students = new List<Student>();
        Students.Add(stu);
        //string s = Convert.ToString(Students.Count);
        MessageBox.Show("Updated");
        txtFirstName.Clear();
        txtLastName.Clear();
        txtCity.Clear();
    }
    private void btnNext_Click(object sender, RoutedEventArgs e)
    {
        // I need to access to the next element by press this button, the current is the member that i has just created 


    }
   }

c#:在WPF中通过按钮访问下一个或上一个元素

要做到这一点,最简单的方法是维护当前在Student对象列表中的位置的某种类型的状态。然后每次单击next按钮时,它都会返回下一个对象并按如下方式递增:

private int counter;
public MainWindow()
{
    InitializeComponent();
    txtFirstName.Clear();
    txtLastName.Clear();
    txtCity.Clear();
    counter = 0;
}
....
private Student getNextStudent()
{
    Student s = Students[counter % (Students.Length - 1)];
    //the modulo operator simply prevents the counter from an IndexOutOfBounds exception 
    //and instead just loops back to the first Student.
    counter++;
    return s;
}
private void btnNext_Click(object sender, RoutedEventArgs e)
{
     Student s = getNextStudent();
     //insert the properties of s into the text fields or whatever you want to do
}

如果您在任何时候对学生列表进行任何更改,则此示例将停止正常工作。您不应该修改Students集合,因为这会使迭代变得混乱。您需要添加额外的代码来处理这种情况。