2014-09-04 35 views
0

背景爲什麼DataGrid在對網格排序後沒有正確地重新綁定到它的源列表?

我有一個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當我排序的網格,然後從中刪除項目?

回答

0

在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()); 
相關問題