[英]Why does the DataTable.Rows.Count not change after deleting rows?
[英]Fire only one event after deleting multiple DataTable rows
我有一個DataTable
有許多行,而DataTable
綁定到DataGrid
。 通過DataGrid
刪除一行或多行后,我需要對重新行進行特定的,非常復雜的檢查。
我訂閱了RowDeleted
事件,並從那里調用了檢查方法。 我的問題是,當通過DataGrid
刪除多行時,會為每一行觸發RowDeleted
事件,每次調用check方法。 由於檢查方法檢查所有剩余的行及其所有列,這對我的應用程序來說是一個很大的減速,也非常多余。 刪除所有選定的行后,運行它就足夠了。
刪除任意數量的行后,有沒有辦法只觸發一個事件?
你可以借助計時器來做到這一點。 聲明全局計時器並設置其屬性:
System.Timers.Timer _delayTimer = new System.Timers.Timer(1000);
_delayTimer.Elapsed += new EventHandler(_delayTimer_Elapsed);
void _delayTimer_Elapsed(object sender, EventArgs e)
{
_delayTimer.Stop();
Dispatcher.Invoke(new Action(UpdateMethodName));
//or - with passing arguments:
Dispatcher.Invoke(new Action<string>(UpdateMethodName), new object[]{"argument"});
}
現在在你的RowDeleted-Event中,你這樣做:
_delayTimer.Stop();
_delayTimer.Start();
因為計時器一次又一次地在RowDeleted事件中重新啟動,所以只有在最后一個處理程序被觸發后才會調用更新邏輯。
我建議你將Checkbox
列添加到datagridview並提供一個delete button
,讓用戶只能通過選中每行的相關復選框來刪除單行或多行。
並添加您的邏輯,檢查按鈕的刪除命令中的重新存儲行。 這將確保您的邏輯將在每次刪除時運行一次,而不管刪除的行數是多少。
我建議你Delete logic in your ViewModel
處理Delete logic in your ViewModel
如:
'Delete' keydown event and bind it to the Command on viewmodel
使用交互性'Delete' keydown event and bind it to the Command on viewmodel
。 DataGrid
的SelectedItems
屬性綁定到Delete Command的CommandParameter
。 DeleteCommand handler, remove the items from the DataGrid's ItemsSource.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.