【问题标题】:C#: accessing the next or previous element by button in WPFC#:在 WPF 中通过按钮访问下一个或上一个元素
【发布时间】:2015-07-06 13:56:35
【问题描述】:

我有一个项目使用按钮访问通用集合中的下一个或上一个元素 学生类有 3 个属性:字符串 lastname、firstname 和 city。 谁能帮我启用它? 我认为它可能与 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 




    }
   }

【问题讨论】:

  • 你是否被 3 个属性卡住了?
  • 不,我认为3个属性都可以,只是想知道如何访问列表中的元素?

标签: c# wpf list next


【解决方案1】:

最简单的方法是保持您当前在Student 对象列表中的某种状态。然后每次单击下一个按钮时,它都会返回下一个对象并像这样递增:

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 集合,因为它会弄乱迭代。您需要添加额外的代码来处理这种情况。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-16
    • 2013-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多