如何将ObservableCollection绑定至GridView?附相关实体类代码
将ObservableCollection绑定到GridView的实现方案
嘿,我来帮你搞定这个绑定的事儿!你已经有了实现INotifyPropertyChanged的ListBoxArticle实体,还有ObservableCollection<ListBoxArticle>类型的LesElem,接下来分步骤就能完成绑定:
1. 后端准备:确保数据源可被绑定
首先要把LesElem设置为公共属性,并且在合适的地方(比如ViewModel构造函数或者页面后台构造函数)初始化并填充数据。另外,你的ListBoxArticle里的IsChecked属性setter没写完,记得补全触发属性变更通知,不然UI不会同步更新:
补全ListBoxArticle的IsChecked属性
private bool isChecked; public bool IsChecked { get { return isChecked; } set { isChecked = value; OnPropertyChanged("IsChecked"); } }
初始化LesElem并设置DataContext
假设你用ViewModel模式(推荐),ViewModel代码示例:
using System.Collections.ObjectModel; public class YourViewModel { public ObservableCollection<ListBoxArticle> LesElem { get; set; } public YourViewModel() { // 初始化集合并添加测试数据 LesElem = new ObservableCollection<ListBoxArticle>(); LesElem.Add(new ListBoxArticle { Chap = 1, Article = "第一章:基础入门", IsChecked = false }); LesElem.Add(new ListBoxArticle { Chap = 2, Article = "第二章:进阶技巧", IsChecked = true }); } }
然后在页面/窗口的后台代码里设置DataContext,让XAML能找到数据源:
public MainWindow() { InitializeComponent(); DataContext = new YourViewModel(); }
2. XAML端:配置ListView与GridView
WPF里的GridView是作为ListView的View来使用的,所以我们需要先创建ListView,绑定它的ItemsSource到LesElem,然后在ListView.View里定义GridView的列,分别绑定实体的各个属性:
<ListView ItemsSource="{Binding LesElem}"> <ListView.View> <GridView> <!-- 绑定Chap属性,显示章节号 --> <GridViewColumn Header="章节" DisplayMemberBinding="{Binding Chap}" Width="80"/> <!-- 绑定Article属性,显示文章标题 --> <GridViewColumn Header="文章标题" DisplayMemberBinding="{Binding Article}" Width="250"/> <!-- 绑定IsChecked属性,用CheckBox实现选择功能 --> <GridViewColumn Header="选择" Width="80"> <GridViewColumn.CellTemplate> <DataTemplate> <CheckBox IsChecked="{Binding IsChecked, Mode=TwoWay}" HorizontalAlignment="Center"/> </DataTemplate> </GridViewColumn.CellTemplate> </GridViewColumn> </GridView> </ListView.View> </ListView>
关键注意点
DisplayMemberBinding默认是OneWay绑定,足够用来显示数据;而CheckBox的IsChecked用TwoWay绑定,能让UI上的选择状态同步回数据源。- 确保你的
ListBoxArticle里的所有属性变更都触发了OnPropertyChanged,这样当数据源属性变化时,UI会自动更新。 - 如果不用ViewModel,也可以把
LesElem直接放在页面后台的公共属性里,然后把DataContext设为this,效果是一样的。
内容的提问来源于stack exchange,提问作者Rose Jack
相关产品推荐
相关产品推荐

