【问题标题】:Why doesn't the DataGrid correctly rebind to its source list after I've sorted the grid?为什么在我对网格进行排序后 DataGrid 没有正确地重新绑定到它的源列表?
【发布时间】:2014-09-04 13:58:26
【问题描述】:

背景

我有一个DataGrid,当我在对数据网格进行排序时从其数据源列表中删除一个项目后,它似乎无法正确显示数据。

这是我的网格:

   <DataGrid Name="fileGrid" 
              SelectionMode="Single" SelectionUnit="FullRow" AutoGenerateColumns="False" 
              HorizontalAlignment="Stretch" VerticalAlignment="Stretch" SelectionChanged="fileGrid_SelectionChanged" PreviewKeyDown="PreviewKeyDownHandler">

        <DataGrid.Columns>
            <!-- other columns removed for brevity -->

            <DataGridTextColumn Header="Installation"  SortMemberPath="Customer.CompanyName" Width="*"
                x:Name="columnCompanyName" 
                Binding="{Binding Path=Customer.CompanyName}"
                IsReadOnly="True">
            </DataGridTextColumn>
        </DataGrid.Columns>
    </DataGrid>

我可以从列表中删除一个项目,例如通过调用

    public void DeleteAndRebind(PanelData panelData)
    {
        _panelDataList.Remove(panelData);
        Rebind();
    }

Rebind() 定义为

    public void Rebind()
    {
        fileGrid.ItemsSource = _panelDataList;
        fileGrid.SelectedItem = _panelDataList.FirstOrDefault();
        fileGrid.Items.Refresh();
    }

网格正确显示,与panelData 对应的行已删除。

问题

但是,如果我按任何列对网格进行排序,然后调用 DeleteAndRebind(panelData),DataGrid 仍然包含我删除的项目,即使 _panelDataList 没有。

问题

当我对网格进行排序然后从中删除一个项目时,为什么DataGrid 不显示更新的_panelDataList

【问题讨论】:

    标签: c# wpf sorting datagrid


    【解决方案1】:

    在 WPF 中,无需分离或重新绑定数据源集合。将数据集合属性数据绑定到ItemsSource 属性后,您应该单独保留ItemsSource 属性和控件。

    <DataGrid ItemsSource="{Binding CollectionProperty}" ... />
    

    所有数据操作都应在集合本身上完成。因此,要更改集合,您只需执行以下操作:

    CollectionProperty = new ObservableCollection<YourDataType>();
    CollectionProperty.FillWithData(); // An imaginary data access method
    

    要从集合中删除一个项目,您只需这样做:

    CollectionProperty.Remove(CollectionProperty.ElementAt(indexOfItemToRemove));
    

    要将项目添加到集合中,您只需执行以下操作:

    CollectionProperty.Add(new YourDataType());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-30
      • 2013-08-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多