简体   繁体   English

当WPF DataGrid中的第一个选定行获得焦点时,如何重新聚焦它?

[英]How can you re-focus the first selected row in the WPF DataGrid when it gains focus?

Simple question with an as-of-yet unfound answer. 尚待解决的简单问题。 We have a WPF DataGrid on our window which supports multi-select. 我们的窗口上有一个WPF DataGrid,它支持多选。 Say it has ten items in it and you have items six through ten selected. 假设其中有十个项目,而您选择了六到十个项目。 If you tab away from the control, when the control gets focus again, the first item is focused but not selected. 如果您远离控件,则当控件再次获得焦点时,第一个项目将被聚焦但未被选中。 The selection still remains on items six through ten. 选择仍保留在项目6到10上。 This is made worse for us because we hide the focus rectangle, instead relying on the selection highlight, which is what the user would expect to happen. 这对我们来说更加糟糕,因为我们隐藏了焦点矩形,而不是依赖于用户希望发生的选择突出显示。

I've tried responding to the IsKeyboardFocusWithinChanged event as shown here, including with and without the dispatcher, figuring maybe something else was changing it after the fact, but still no avail. 我试过响应IsKeyboardFocusWithinChanged事件,如此处所示,包括使用和不使用调度程序,弄清楚事实发生后,也许有其他事情正在改变它,但仍然无济于事。

private void TestDataGrid_IsKeyboardFocusWithinChanged(object sender, DependencyPropertyChangedEventArgs e)
{
    if(!(bool)e.NewValue)
        return;

    Dispatcher.Invoke(new Action(() => 
    {
        var firstSelectedItem = VariableValuesDataGrid.SelectedItem;

        if(firstSelectedItem != null)
            VariableValuesDataGrid.CurrentItem = firstSelectedItem;
    }), DispatcherPriority.Background);
}

Any idea how to get around this? 任何想法如何解决这个问题?

I'm not really that familiar with the WPF DataGrid but I suspect you must be dealing with the same issues of the old forms DataGridView. 我对WPF DataGrid并不是很熟悉,但是我怀疑您必须处理与旧表格DataGridView相同的问题。

Setting the selected row only highlights and doesn't actually focus it. 设置选定的行只会突出显示,而不会真正使其聚焦。 And the CurrentRow property is unfortunately private but the CurrentCell property is not and can be used to set the selection instead. 而且,不幸的是, CurrentRow属性是私有的,但是CurrentCell属性不是,并且可以用来设置选择。

myDataGrid.CurrentCell = myDataGrid.Rows[i].Cells[0];
myDataGrid.Rows[i].Selected = True;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM