【问题标题】:How can you re-focus the first selected row in the WPF DataGrid when it gains focus?当 WPF DataGrid 获得焦点时,如何重新聚焦第一个选定的行?
【发布时间】:2015-09-17 23:11:04
【问题描述】:

一个简单的问题,目前还没有找到答案。我们的窗口上有一个支持多选的 WPF DataGrid。假设它有十个项目,并且您选择了项目六到十。如果您离开控件,当控件再次获得焦点时,第一个项目将获得焦点但未选中。选择仍然保留在第 6 到第 10 项上。这对我们来说更糟,因为我们隐藏了焦点矩形,而不是依赖于选择突出显示,这是用户期望发生的。

我已经尝试响应 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);
}

知道如何解决这个问题吗?

【问题讨论】:

  • 因此,如果您的数据网格获得焦点,您希望第一个项目被选中并获得焦点,对吧?
  • 关闭。我希望第一个选定的行成为焦点。

标签: c# wpf datagrid .net-4.0


【解决方案1】:

我对 WPF DataGrid 不是很熟悉,但我怀疑您必须处理与旧表单 DataGridView 相同的问题。

设置选定的行只会突出显示而不是实际聚焦它。不幸的是,CurrentRow 属性是私有的,但 CurrentCell 属性不是,可以用来设置选择。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-04
    • 2011-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多