我有以下请求:通过单击按钮添加和删除数据网格(WPF)中的项目。当用户在datagrid中添加新行(新项)时,我想在这个新项上自动进入编辑模式。如果SelectionUnit是Cell,这将有效,但我希望它是FullRow。我在调用datagrig.BeginEdit()之前尝试将SelectionUnit更改为Cell,但它不起作用。
以下是代码:
<DataGrid Name="dgDatagrid" Margin="20,20,3,3" CanUserSortColumns="True" ItemsSource="{Binding AllItems}"
AutoGenerateColumns="False" SelectionUnit="FullRow" SelectionMode="Single" CanUserAddRows="False" CanUserDeleteRows="False"
CanUserResizeRows="True" CanUserReorderColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="First column name" MinWidth="160" Binding="{Binding Path=FirstColumn}"/>
<DataGridCheckBoxColumn Header="Second column name" MinWidth="100" Binding="{Binding Path=SecondColumn, UpdateSourceTrigger=PropertyChanged}"/>
</DataGrid.Columns>
</DataGrid>
后台功能:
private void AddNewItem()
{
var newItem = new Item();
AllItems.Add(newItem);
dgDatagrid.ScrollIntoView(newItem );
dgDatagrid.SelectedItem = newItem ;
var selectedIndex = dgDatagrid.SelectedIndex;
dgDatagrid.SelectionUnit = DataGridSelectionUnit.Cell;
dgDatagrid.CurrentCell = new DataGridCellInfo(dgDatagrid.Items[selectedIndex], dgDatagrid.Columns[0]);
dgDatagrid.BeginEdit();
dgDatagrid.SelectionUnit = DataGridSelectionUnit.FullRow;
}