簡體   English   中英

單擊“刪除”鍵按鈕刪除DataGrid行(WPF)

[英]Delete DataGrid row (WPF) by clicking Delete key button

我有基於桌面的WPF 4應用程序。 在這個應用程序的一個窗口中,我有DataGrid數據,與SQL Server數據庫綁定(通過ADO.NET實體框架)。 為了操作數據,我有一個刪除按鈕,它從DataGrid中刪除所選行並調用SaveChanges()方法。

現在我想添加對鍵盤操作的支持,例如我想讓用戶通過選擇並單擊Delete keyboard按鈕來刪除該行。

如果我在窗口XAML中設置CanUserDeleteRows="True" ,它會刪除所選行,但不會提交數據庫,換句話說,它不會調用SaveChanges()方法。

我試圖將keyDown事件處理程序添加到DataGrid檢查if (e.Key == Key.Delete) ,因此運行remove方法刪除所選行並調用SaveChanges()方法,但它不起作用。

我的問題是如何向DataGrid添加鍵盤事件處理程序,它將刪除所選行並調用SaveChanges()方法或只運行我自己的方法,該方法處理從DataGrid刪除行並提交到DB。

當然,如果您對我的問題有任何其他想法,請隨時提出建議。

您是否嘗試過使用PreviewKeyDown事件? 像這樣的東西

<DataGrid x:Name="dataGrid" PreviewKeyDown="dataGrid_PreviewKeyDown">

private void dataGrid_PreviewKeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Delete)
    {
        var dataGrid = (DataGrid)sender;
        // dataGrid.SelectedItems will be deleted...
        //...
    }
}

與Ben的相同,但所有人必須做的是通過將屬性CanUserDeleteRows設置為true來啟用屬性,並且刪除按鈕將激活刪除。

如下面在DataGrid XAML所示:

CanUserDeleteRows="True"

或者您可以使用CommandManager,如果選擇了行,則只刪除該行(如果單元格正在編輯,則會備份)。

將它放在Datagrid所在的Window中。

CommandManager.RegisterClassInputBinding(typeof(DataGrid),
                new InputBinding(DataGrid.DeleteCommand, new KeyGesture(Key.Delete)));

我看到你成功了,但也許這對其他人在搜索結果中發表這篇文章會很有用。 您需要覆蓋DataGrid的OnCanExecuteDelete方法,如:

public class MyDataGrid : DataGrid
{
    protected override void OnCanExecuteDelete(CanExecuteRoutedEventArgs e)
    {
        foreach(DataRowView _row in this.SelectedItems) //assuming the grid is multiselect
        {
            //do some actions with the data that will be deleted
        }
        e.CanExecute = true; //tell the grid data can be deleted
    }
}

但這僅僅是為了操縱純圖形。 要保存到數據庫或其他操作,請使用數據網格的數據源。

暫無
暫無

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

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