在XAML代码段下面,有一个与ICollectionView SysPropViewCollection的简单数据绑定,这不会导致数据集中显示的任何数据--但是,如果我将绑定更改为ObservableCollection SystemPropertiesList,则按预期填充数据。您能帮助指出在使用ICollectionView时绑定结构/用法是否不同吗?在构建/运行应用程序时,VS2019中没有报告绑定失败。
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#
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();
}
}发布于 2022-11-03 08:44:58
更改SysPropCollectionView属性的值,但不通知它。我不知道您使用的是哪个VM基类,所以我无法确定地编写。
应该有这样的东西:
public ObservableCollection<SystemProperties> SystemPropertiesList
{
get => systemPropertiesList;
set
{
if (!SetProperty(ref systemPropertiesList, value, () => SystemPropertiesList))
return;
SysPropCollectionView = CollectionViewSource.GetDefaultView(systemPropertiesList);
RaisePropertyChanged(nameof(SysPropCollectionView));
}
}我还建议您检查SetProperty方法的重载。在典型的实现中,通常存在这样的重载:
set
{
if (!SetProperty(ref systemPropertiesList, value))
return;补编.
为了避免这样的错误,我宁愿使用替换的SysPropCollectionView属性类型并进行不同的实现。因为为DefaultView创建一个属性是毫无意义的。对于所有使用过的集合,WPF都会自动执行此操作。
public CollectionViewSource SysPropCollectionViewSource {get;} = new();
private ObservableCollection<SystemProperties> systemPropertiesList;
public ObservableCollection<SystemProperties> SystemPropertiesList
{
get => systemPropertiesList;
set
{
if (SetProperty(ref systemPropertiesList, value))
SysPropCollectionViewSource.Source = value;
}
}实际上,您可以删除SystemPropertiesList属性并使用SysPropCollectionViewSource.Source附加属性。这是一个DependencyProperty,所以不需要通知就可以更改它。
https://stackoverflow.com/questions/74296186
复制相似问题