WPF DataGrid绑定ICollectionView无数据显示问题求助
在WPF项目中,DataGrid绑定ICollectionView类型的SysPropCollectionView后无数据显示,但绑定ObservableCollection类型的SystemPropertiesList时能正常加载数据,且VS2019构建运行时无绑定失败提示,想知道ICollectionView的绑定构造或使用是否存在差异?
XAML代码
<DataGrid Style="{DynamicResource DataGridStyle1}" IsReadOnly="True" ColumnWidth="Auto" AutoGenerateColumns="False" RowHeight="20" ItemsSource="{Binding ElementName=ConfigEditor, Path=SysPropViewModel.SysPropCollectionView}" Grid.Row="2" Grid.ColumnSpan="2" Grid.Column="0" IsSynchronizedWithCurrentItem="True"> <DataGrid.Columns> <DataGridTextColumn Header="Environment" Binding="{Binding Path=Environment}" MinWidth="100" Width="Auto"> </DataGridTextColumn> </DataGrid.Columns> </DataGrid>
C# ViewModel代码
private ObservableCollection<SystemProperties> systemPropertiesList; public ICollectionView SysPropCollectionView { get; private set; } public ObservableCollection<SystemProperties> SystemPropertiesList { get => systemPropertiesList; set { if (!SetProperty(ref systemPropertiesList, value, () => SystemPropertiesList)) return; SysPropCollectionView = CollectionViewSource.GetDefaultView(systemPropertiesList); SysPropCollectionView.Refresh(); } }
问题原因
你当前的SysPropCollectionView是私有setter且未触发属性变更通知的属性:当在SystemPropertiesList的setter中重新赋值SysPropCollectionView时,WPF绑定系统无法感知到这个属性的变化。而ObservableCollection本身实现了INotifyCollectionChanged接口,绑定它时集合内容的变化能被自动感知,但ICollectionView属性本身的更新没有通知到UI。
解决方法
给
SysPropCollectionView添加属性变更通知
修改SysPropCollectionView的定义,让它在赋值时触发PropertyChanged事件,确保UI能收到属性更新的通知:private ICollectionView _sysPropCollectionView; public ICollectionView SysPropCollectionView { get => _sysPropCollectionView; private set => SetProperty(ref _sysPropCollectionView, value); }这样当你在
SystemPropertiesList的setter中给它赋值时,绑定系统会立刻感知到并更新DataGrid的数据源。可选:提前初始化ICollectionView
在ViewModel的构造函数中提前初始化SysPropCollectionView,避免初始状态下属性为null:public YourViewModel() { systemPropertiesList = new ObservableCollection<SystemProperties>(); SysPropCollectionView = CollectionViewSource.GetDefaultView(systemPropertiesList); }
核心差异说明
ObservableCollection是集合容器,通过INotifyCollectionChanged接口通知集合内容的增删改变化,绑定后UI会自动同步这些变化。ICollectionView是集合的视图包装,它本身是一个ViewModel属性,需要遵循WPF的INotifyPropertyChanged规则——属性值变化时必须触发通知,否则UI不会更新绑定。另外,ICollectionView依赖底层集合,只要底层集合是ObservableCollection,集合内容变化会自动同步到视图,但视图实例本身的替换必须通过属性变更通知让UI知晓。
内容的提问来源于stack exchange,提问作者rahul

