如何将光标设置在绑定到数据 table 的数据网格中空行的第一个单元格上

How to set the cursor on the first cell of an empty row in datagrid which is bound to a data table

我有一个绑定到数据表的数据网格。我想知道 - 我们如何将光标显示为在绑定到数据表的此数据网格的空行的第一个单元格中闪烁。此外,当用户通过按回车键向此 datatable/datagrid 添加新的空行时,光标应在新添加的空行的第一个单元格上闪烁。

这是目前显示的 UI,但用户可能不知道在何处插入值,因为最后一个空行上没有闪烁的光标。

代码如下:

View.xaml

<DataGrid x:Name="MyGrid" ItemsSource="{Binding MyDataTable, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"   
                          VerticalAlignment="Top"                           
                          Height="400"
                          Width="Auto"
                          SelectionMode="Single"                        
                          AutoGenerateColumns="True"
                          GridLinesVisibility ="Vertical"
                          Background="Transparent"
                          CanUserResizeColumns="True"
                          CanUserReorderColumns="False"
                          CanUserResizeRows="False"                
                          BorderThickness="0" 
                          CanUserAddRows="True" 
                          RowHeaderWidth="0">                                                  
</DataGrid>

ViewModel.cs

private DataTable _MyDataTable;

public DataTable MyDataTable
{
    get { return _MyDataTable; }
    set { SetProperty(ref _MyDataTable, value); }
}

您所说的 "setting the blinking cursor" 被称为聚焦(当文本框聚焦时,它会显示闪烁的插入符号;当按钮聚焦时,Enter 键会触发它的点击等)

这是一篇详细的文章,其中包含多个示例,说明如何在数据网格中聚焦 rows/cells:https://social.technet.microsoft.com/wiki/contents/articles/21202.wpf-programmatically-selecting-and-focusing-a-row-or-cell-in-a-datagrid.aspx