如何在WPF中根据学生集合数量多次复用StudentView视图?
WPF 批量显示自定义用户控件问题
现有代码
1. StudentView.xaml 用户控件
<Grid> <TextBlock Text="{Binding StudentName}"/> <TextBlock Text="{Binding StudentID}"/> </Grid>
2. Student.cs 模型类
private string _StudentName = null; public string StudentName{ get => _StudentName; set {_StudentName = value; OnPropertyChange("StudentName");} } private string _StudentID = null; public string StudentID{ get => _StudentID ; set {_StudentID = value; OnPropertyChange("StudentID");} }
3. MainViewModel 中的集合定义
ObservableCollection<Student> Students = new ObservableCollection<Student>(); // 填充Students集合的逻辑 NumOfStudents = Students.Count();
4. 主窗口XAML代码
<StackPanel> <local:StudentView/> </StackPanel>
问题
我是WPF新手,目前知道怎么把local:StudentView绑定到单个学生对象,但想实现根据集合中学生的数量自动重复显示StudentView——比如集合里有5个学生,就显示5次这个控件,求实现方法。
实现方法
用WPF的ItemsControl控件就能轻松实现批量绑定,它会自动根据集合元素数量生成对应控件,步骤如下:
- 修改主窗口XAML,替换单独的
StudentView为ItemsControl,绑定集合并指定模板:
<StackPanel> <ItemsControl ItemsSource="{Binding Students}"> <ItemsControl.ItemTemplate> <DataTemplate> <local:StudentView/> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> </StackPanel>
- 将ViewModel的集合改为公开属性,原代码中
Students是私有字段,需改为公开属性才能被绑定:
public ObservableCollection<Student> Students { get; set; } = new ObservableCollection<Student>();
- 确保主窗口绑定上下文正确,在主窗口构造函数中设置
DataContext为MainViewModel实例:
public MainWindow() { InitializeComponent(); DataContext = new MainViewModel(); }
原理说明
ItemsControl是WPF专门用于展示集合数据的基础控件,会遍历ItemsSource绑定的集合,为每个元素创建ItemTemplate内定义的控件实例。- 每个
StudentView的DataContext会自动关联集合中对应的Student对象,因此原有的{Binding StudentName}、{Binding StudentID}绑定会自动生效,无需额外配置。
内容的提问来源于stack exchange,提问作者Jtastic
相关产品推荐
相关产品推荐

