我正在努力让学生注册/退学,但我不完全确定如何将特定学生添加到特定课程。
我有一个Course and Student课程,然后是一个带有组合框的xaml窗口,以及带有相应按钮的列表框。 当我现在按下注册时,它只需要选择的学生并将其添加到"注册学生"文本框显示名称,但它实际上并没有将其分配给选定的课程。
我到目前为止的代码:
public MainWindow()
{
InitializeComponent();
Course bsc = new Course("BSc(Hons) Applied Computing");
Course hnd = new Course("Higher National Diploma (HND) Applied Computing");
Course partTime = new Course("Computer Science Part Time (MSc)");
Student andy = new Student("Andy", "Watt");
Student dave = new Student("Dave","Newbold");
Student daniel = new Student("Daniel","Brown");
lbCourses.Items.Add(bsc);
lbCourses.Items.Add(hnd);
lbCourses.Items.Add(partTime);
cbStudents.Items.Add(andy);
cbStudents.Items.Add(dave);
cbStudents.Items.Add(daniel);
}
和注册按钮点击代码:
private void butEnroleStudent_Click(object sender, RoutedEventArgs e)
{
cbStudents.SelectedItem.ToString();
lbEnroledStudents.Items.Add(cbStudents.SelectedItem);
}
但我不知道从哪里开始。我的主要问题是我不知道如何选择学生和课程而不是字符串值。
答案 0 :(得分:0)
正如BradleyDotNET所建议的那样,MVVM将更容易使用,特别是如果你的UI会变得更复杂。此外,像这样的任何应用程序很可能在幕后依赖于数据库,因此您可能希望绑定所有数据控件。
那就是说,这是一个可以实现你想要做的事情的样本。
假设你的Student
课程看起来像这样:
private class Student
{
public String FirstName { get; set; }
public String Surname { get; set; }
public Student(String firstName, String surname)
{
FirstName = firstName;
Surname = surname;
}
public override string ToString()
{
return FirstName + " " + Surname;
}
}
你的Course
课程就像这样:
private class Course
{
public String Name { get; set; }
public List<Student> EnrolledStudents { get; set; }
public Course(String name)
{
Name = name;
EnrolledStudents = new List<Student>();
}
public override string ToString()
{
return Name;
}
}
(请注意,我已添加List
来存储在指定课程中注册的学生)
不是添加Items
和ListBox
的{{1}}属性,而是创建我们可以绑定到的集合:
ComboBox
构建测试数据然后如下所示:
private List<Student> _students;
private List<Course> _courses;
然后单击注册按钮
_courses = new List<Course>();
_courses.Add(new Course("BSc(Hons) Applied Computing"));
_courses.Add(new Course("Higher National Diploma (HND) Applied Computing"));
_courses.Add(new Course("Computer Science Part Time (MSc)"));
_students = new List<Student>();
_students.Add(new Student("Andy", "Watt"));
_students.Add(new Student("Dave", "Newbold"));
_students.Add(new Student("Daniel", "Brown"));
lbCourses.ItemsSource = _courses;
cbStudents.ItemsSource = _students;
最后,要在点击课程时显示private void butEnroleStudent_Click(object sender, RoutedEventArgs e)
{
if (lbCourses.SelectedIndex >= 0 && cbStudents.SelectedIndex >= 0)
{
// Both a student and course are selected
Course selectedCourse = (Course)lbCourses.SelectedItem;
Student studentToAdd = (Student)cbStudents.SelectedItem;
if (!selectedCourse.EnrolledStudents.Contains(studentToAdd))
{
// Course does not already contain student, add them
selectedCourse.EnrolledStudents.Add(studentToAdd);
lbEnroledStudents.Items.Refresh();
}
}
}
中注册的学生,您需要在xaml中连接一个新的事件处理程序:
lbEnroledStudents
在后面的代码中:
<ListBox x:Name="lbCourses" SelectionChanged="lbCourses_SelectionChanged"></ListBox>