问题
I have Student table, Course table and a StudentCourse table. On my WPF, I'm making "Student" selections with combo box. How can I display the corresponding Course and its properties(CourseID, CourseName, Credit) in a listview, using ObservableCollection?. Here's my code for the combo box SelectionChanged event
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);
回答1:
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;
}
来源:https://stackoverflow.com/questions/10196127/listview-to-display-observableselection