簡體   English   中英

刪除多個DataTable行后僅觸發一個事件

[英]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如:

  1. 處理'Delete' keydown event and bind it to the Command on viewmodel使用交互性'Delete' keydown event and bind it to the Command on viewmodel
  2. DataGridSelectedItems屬性綁定到Delete Command的CommandParameter
  3. DeleteCommand handler, remove the items from the DataGrid's ItemsSource.
  4. 刪除項目后,您可以運行檢查

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM