且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

DataGrid以编程方式选择最后一个单元格

更新时间:2022-12-27 17:37:01

您可能需要根据是否有新项目行可见或不可见,而是适用于我。

You may have to fiddle with the offsets depending on whether there's an new item row visible or not, but this works for me.

    private bool _hasHadInitialFocus;

    private void DataGridGotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
    {
        if (!_hasHadInitialFocus)
        {
            if (dataGrid.Items.Count - 2 >= 0 && dataGrid.Columns.Count - 1 >= 0)
            {
                var dataGridCellInfo = new DataGridCellInfo(
                    dataGrid.Items[dataGrid.Items.Count - 2], dataGrid.Columns[dataGrid.Columns.Count - 1]);

                dataGrid.SelectedCells.Clear();
                dataGrid.SelectedCells.Add(dataGridCellInfo);
                dataGrid.CurrentCell = dataGridCellInfo;
                dataGrid.BeginEdit();
            }

            _hasHadInitialFocus = true;
        }
    }

我注意到点击网格会留下一个单元格和编辑模式下的目标单元格。如果需要,解决方案是:

I noticed that clicking into the grid leaves one cell selected and the target cell in edit mode. A solution to this if required is:

    private void DataGridGotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
    {
        EditCell();
    }

    private void PreviewMouseLBDown(object sender, MouseButtonEventArgs e)
    {
        if (!_hasHadInitialFocus)
        {
            e.Handled = true;
            EditCell();
        }
    }

    private void EditCell()
    {
        if (!_hasHadInitialFocus)
        {
            if (dataGrid.Items.Count - 2 >= 0 && dataGrid.Columns.Count - 1 >= 0)
            {
                var dataGridCellInfo = new DataGridCellInfo(
                    dataGrid.Items[dataGrid.Items.Count - 2], dataGrid.Columns[dataGrid.Columns.Count - 1]);

                dataGrid.SelectedCells.Clear();
                dataGrid.SelectedCells.Add(dataGridCellInfo);
                dataGrid.CurrentCell = dataGridCellInfo;
                dataGrid.BeginEdit();
            }

            _hasHadInitialFocus = true;
        }
    }