Domanda

I have a example Method OnKeyDownHandler:

    private void OnKeyDownHandler(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Delete)
         {
            if (sender == listBox)
                listItemDelete();
            if (sender == dataGrid)
                dataGridItemDelete();
        }
    }

I have a DataGrid and a ListBox. Now i want to delete a Item when i press the Delete-Key and an item is selected.

Now we go through the following situations:

I have a SelectedItem in my listBox and the focus on it. When I press the Deletey-Key the OnKeyDownHandler-Event would be triggered.

I have a SelectedItem in my dataGrid and the focus on it. When i press the Delete-Key, the OnkeyDownHandler-Event wouldn't be triggered.

When I press any other Key like the Paste-Key, the OnKeyDownHandler-Event would be triggered.

The event is not called when I press the Delete-Key on my dataGrid. Why is that? I can not explain it.


Edit: XAML-Code

<DataGrid KeyDown="OnKeyDownHandler" />

<ListBox KeyDown="OnKeyDownHandler" />
È stato utile?

Soluzione

The KeyDown event on your DataGrid is being handled by the active cell. The DataGridView control is handling the event, not your code-behind. You could try using the PreviewKeyDown event instead of KeyDown for the DataGrid.

Altri suggerimenti

I guess you OnKeyDownHandler is attached to the listbox and not to the datagrid. You need something like dataGrid.OnKeyDown += OnKeyDownHandler; in you Window_Loaded or Page_Loaded or in XAML

<DataGrid ... OnKeyDown="OnKeyDownHandler" ... ></DataGrid>
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top