Home > Blockchain >  WPF - Datagrid ICollectionView binding
WPF - Datagrid ICollectionView binding

Time:11-03

Below XAML snippet has a simple datagrid binding to a ICollectionView SysPropViewCollection which doesn't result in the any data shown in the datagrid - However, if I change the binding to an ObservableCollection SystemPropertiesList the datagrid is populated as expected. Can you help point out if binding constructs/usage is different when using ICollectionView? There are no binding failures reported in VS2019 when I build/run the application.

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();
    }
}

CodePudding user response:

You change the value of the SysPropCollectionView property, but you don't notify it. I don't know which VM base class you are using, so I can't write for sure.
There should be something like this:

public  ObservableCollection<SystemProperties> SystemPropertiesList
{
    get => systemPropertiesList;
    set
    {
        if (!SetProperty(ref systemPropertiesList, value, () => SystemPropertiesList))
            return;
        SysPropCollectionView = CollectionViewSource.GetDefaultView(systemPropertiesList);
        RaisePropertyChanged(nameof(SysPropCollectionView));
    }
}

I also advise you to check the overloads of the SetProperty method. In typical implementations, there is usually an overload like this:

    set
    {
        if (!SetProperty(ref systemPropertiesList, value))
            return;
  • Related