WPF DataGrid - clicking column header does NOT transfer focus to the grid

Aug 5, 2009 at 7:07 PM

DataGrid column headers have the FocusableProperty dependency property set to false. Thus if the focus is outside the datagrid and the user clicks on a column header, the focus is NOT transferred to the datagrid. This is a problem if the datagrid has a context menu or keyboard input bindings: the context menu items will be disabled and the key bindings will not fire, since the bindings are not in the visual tree path from the focused item to the root.

End result: user clicks on grid header & context menu/shortcut keys do not work. :-(

Short term workaround: add an event handler for the PreviewMouseUp event + set the focus to the grid.

        private void SetFocusIfNotOnThis(object sender, MouseEventArgs args)
        {
            DependencyObject focusedObject = Keyboard.FocusedElement as DependencyObject;

            if (focusedObject==null || 
                VisualTreeHelpers.FindElementOfTypeInParentTree<DataGrid>(focusedObject)==null)
            {
                Keyboard.Focus(this);
            }
        }