正如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
p我們可以綁定到你的ListBox
和ComboBox
創建集合roperty:
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();
}
}
}
最後,在點擊課程時向lbEnroledStudents
顯示註冊的學生,您需要連接一個新的e發泄在XAML處理程序:
<ListBox x:Name="lbCourses" SelectionChanged="lbCourses_SelectionChanged"></ListBox>
而且在後面的代碼:
private void lbCourses_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Course selectedCourse = (Course)lbCourses.SelectedItem;
lbEnroledStudents.ItemsSource = selectedCourse.EnrolledStudents;
}
您會考慮使用MVVM代替這種直接的UI操作的?它的*方式*更容易,當涉及到這樣的東西... – BradleyDotNET 2015-03-02 23:34:14