Wpf 控件不聚焦

Wpf 控件不聚焦,wpf,wpf-controls,wpfdatagrid,Wpf,Wpf Controls,Wpfdatagrid,我有一个带有多个子控件的WPF用户控件,我使用以下代码以编程方式关注DataGrid和TextBox: searchTextBox.Focus(); 及 searchTextBox正常聚焦,但dataGrid不聚焦(键盘聚焦停留在其他控件上)。下面我提供了隐藏searchTextBox并将焦点移到productGrid的完整源代码(searchPanel是searchTextBox的父网格): 什么会导致这种情况 Thnx.似乎productGrid.可聚焦的属性设置为“false”。您只需将

我有一个带有多个子控件的WPF用户控件,我使用以下代码以编程方式关注DataGrid和TextBox:

searchTextBox.Focus();

searchTextBox正常聚焦,但dataGrid不聚焦(键盘聚焦停留在其他控件上)。下面我提供了隐藏searchTextBox并将焦点移到productGrid的完整源代码(searchPanel是searchTextBox的父网格):

什么会导致这种情况


Thnx.

似乎productGrid.
可聚焦的
属性设置为
“false”
。您只需将其设置为
“True”
,您的代码就可以正常工作,无需调用
键盘.Focus()
方法。

请将注释作为注释而不是答案添加。Focusable设置为true(我使用调试器检查了它),但看起来像是部分聚焦的productGrid,因为它用蓝色矩形突出显示所选行,但虚线矩形指示键盘焦点保留在其他控件上。请看,完全未聚焦的网格看起来是这样的:我不确定标准网格,但它可能会关注自身并处理键盘事件以在行之间导航等。因此,如果这只是一个视觉问题,而不是行为问题,我建议您在代码中将DataGrid.FocusVisualStyle属性设置为null(或在XAML中将其设置为{x:null})。桑卡兰:对不起,我确信我的想法就是这个问题的答案。
productGrid.Focus();

productGrid.Focus(dataGrid); //tried this but it does not help
    private void Execute_CancelCommand(object sender, ExecutedRoutedEventArgs e)
    {
        if (searchPanel.Visibility == Visibility.Visible)
        {
            searchPanel.Visibility = Visibility.Collapsed;

            searchTextBox.Clear();

            searchTextBox.Background = Brushes.White;

            //the focus stays on the splitter for some reason
            productGrid.Focus();

            Keyboard.Focus(productGrid);
        }
    }