2012-05-12 699 views
2

我是WPF的新手。我想從datagrid運行時刪除行。當我嘗試刪除像這樣的行時Wpf Datagrid刪除行問題

Datagrid.Items.Remove(eRow);

它給了我一個錯誤「錯誤是:在ItemsSource正在使用時操作無效,而是使用ItemsControl.ItemsSource來訪問和修改元素。

我在線閱讀,您可以使用ObservationCollection和InotifyPropertyChangedEvent但我不知道如何實現它。

我刪除這樣

enter image description here

按鈕,這是數據網格

<ctrls:RhinoDataGrid x:Name="dataGrid" Grid.Row="1" Margin="5" ItemsSource="{Binding Model.CurrentDataTable}" 
          Style="{StaticResource RhinoDataGridBaseStyle}" IsReadOnly="{Binding Model.IsLinkFile}" 
          SelectedValue="{Binding Model.CurrentDataRow}" SelectedValuePath="Row" 
           > 

      </ctrls:RhinoDataGrid> 

請幫助我。謝謝。

回答

5

您的DataGrid的ItemsSource在Model.CurrentDataTable上具有綁定。如果你想刪除一行,你將不得不刪除該集合中的項目。但是DataGrid不會注意到該修改,如果該集合沒有實現INotifyCollectionChanged

.NET有一個內置的ObservableCollection,它實現INotifyCollectionChanged。如果您將此集合類型用於CurrentDataTable,則在修改集合時,DataGrid將自行更新。

+0

ObservableCollection dtCollection = this.ItemsSource as ObservableCollection ; dtCollection.CollectionChanged + = new NotifyCollectionChangedEventHandler(dtCollection_CollectionChanged);像這樣的權利? –

+0

好吧,沒有。您的基礎數據列表(原始文章中的Model.DataTable)應該是一個ObservableCollection ,因此您可以將它用作XAML代碼中的綁定源。 DataGrid將自動附加到列表的CollectionChanged事件。請閱讀MSDN上的備註和示例。 [數據綁定部分](http://msdn.microsoft.com/en-us/library/ms752347.aspx)也應該對您有所幫助。 – rumpelstiefel

1

WPF數據綁定意味着你很少直接操縱用戶界面。你要做的是直接從UI上的網格控件中刪除該行,這就是你如何在Winforms中接近事物。

使用WPF數據綁定,用戶界面會對基礎數據作出反應。因此,在您的情況下,網格綁定到(或「觀看」)綁定指定的ItemsSource的內容:Binding Model.CurrentDataTable

要刪除一行,您需要將其從基礎數據中移除,UI將自動反映改變。

這是ObservableCollectionINotifyPropertyChanged都是關於 - 你真的需要對他們閱讀,如果你正在做WPF發展!

+0

是的,你是絕對正確的,我只想達到目的。但我的刪除按鈕是ICommand。我怎樣才能做到這一點。 _removeSelectedRowCommand = new DelegateCommand(RemoveSelectedRow,true); Private void RemoveSelectedRow() DataView view = this.ItemsSource as DataView; view.Table.Rows [this.SelectedRowIndex]。刪除(); this.Items.Refresh(); } –