1

我有学生表、课程表和学生课程表。在我的 WPF 上,我正在使用组合框进行“学生”选择。如何使用 ObservableCollection 在列表视图中显示相应的课程及其属性(CourseID、CourseName、Credit)?这是我的组合框 SelectionChanged 事件的代码

 private void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        int MySelect = (int)this.comboBox1.SelectedValue;
        var SelectedStudent = db.Students.Include("StudentCourses.Course").SingleOrDefault(f => f.StudentID == MySelect);
4

1 回答 1

3

If you're not already, I would highly recommend using a MVVM styled approach. Your ListView's ItemsSource should be bound to an ObservableCollection in your ViewModel and your ComboBox's SelectedItem should also be bound to a propety on your ViewModel. When the SelectedItem changes and calls the property's setter update the ObservableCollection that your ListView is bound to.

Update:

Here's a partially implemented solution:

XAML:

<DockPanel>
    <ComboBox ItemsSource="{Binding Students}" SelectedItem="{Binding SelectedComboItem}" DockPanel.Dock="Top">
        <ComboBox.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Name}"/>
            </DataTemplate>
        </ComboBox.ItemTemplate>
    </ComboBox>

    <ListView ItemsSource="{Binding StudentCourses}">
        <ListView.ItemTemplate>
            <DataTemplate>
                <StackPanel>
                    <TextBlock Text="{Binding Name, StringFormat={}Name: {0}}"/>
                    <TextBlock Text="{Binding Id, StringFormat={}Id: {0}}"/>
                    <TextBlock Text="{Binding Credit, StringFormat={}Credit: {0}}"/>
                </StackPanel>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</DockPanel>

Code:

public class Student
{
    public string Name { get; set; }
    public List<string> CourseIds { get; set; }
} 


public class Course
{
    public string Name { get; set; }
    public string Id { get; set; }
    public int Credit { get; set; }
}


public class ViewModel : INotifyPropertyChanged
{
    public ObservableCollection<Course> StudentCourses { get; set; }
    public ObservableCollection<Student> Students { get; set; }


    public Student SelectedComboItem
    {
        get { return selectedComboItem_; }
        set {
            selectedComboItem_ = value;
            StudentCourses.Clear();
            foreach(Course course in courses_)
                if(selectedComboItem_.CourseIds.Contains(course.Id))
                    StudentCourses.Add(course);
            PropertyChanged(this, new PropertyChangedEventArgs("SelectedComboItem"))    ;
        }
    }


    private List<Course> courses_ = new List<Course>();
    private Student selectedComboItem_;


    ... // Read DB and build collections

    public event PropertyChangedEventHandler PropertyChanged;
}
于 2012-04-17T17:43:48.350 回答