Home > OS >  C# WPF Text of a cell is highlighted after starting editing
C# WPF Text of a cell is highlighted after starting editing

Time:07-05

enter image description here

Hello, i load the contents of a database (mdb) into a datatable object and display them in a datagrid (WPF) so that I can edit them. As soon as I start editing a cell (pressing F2), the entire text is selected. Is there a way to prevent this marking?

My Datagrid in WPF:

<DataGrid VirtualizingStackPanel.VirtualizationMode="Standard" Height="750" Width="1920" CanUserResizeColumns="True" CanUserReorderColumns="False" CanUserResizeRows="False" RowHeight="25" FrozenColumnCount="1" x:Name="DataGrid1" CanUserAddRows="False" CanUserSortColumns="False" AutoGenerateColumns="False" FontSize="13" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="0,0,0,120" SelectionUnit="CellOrRowHeader" SelectionMode="Extended">

                <DataGridTextColumn Width="450" Header=" Column1 " Binding="{Binding Column1}">
                    <DataGridTextColumn.EditingElementStyle>
                        <Style TargetType="TextBox">
                            <Setter Property="MaxLength" Value="150"></Setter>
                        </Style>
                    </DataGridTextColumn.EditingElementStyle>
                </DataGridTextColumn>

                <DataGridTextColumn Width="120" Header=" Column2 " Binding="{Binding Column2}">
                    <DataGridTextColumn.EditingElementStyle>
                        <Style TargetType="TextBox">
                            <Setter Property="MaxLength" Value="10"></Setter>
                        </Style>
                    </DataGridTextColumn.EditingElementStyle>
                </DataGridTextColumn>
            </DataGrid.Columns>

            <DataGrid.RowStyle>
                <Style TargetType="DataGridRow">
                    <EventSetter Event="KeyDown"  Handler="DATAGRID_Keydown" ></EventSetter>
                </Style>
            </DataGrid.RowStyle>

</DataGrid>

My C# Code:

private void DATAGRID_Keydown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Tab | e.Key == Key.F2)
    {
      DataGrid1.BeginEdit();
    }
}

CodePudding user response:

you can use the PreparingCellForEdit event for the DataGrid:

XAML

<DataGrid ... PreparingCellForEdit="DataGrid_PreparingCellForEdit">

C# (It will place the cursor at the end of the current cell text)

private void DataGrid_PreparingCellForEdit(object sender, DataGridPreparingCellForEditEventArgs e)
{
    ((TextBox)e.EditingElement).SelectionStart = ((TextBox)e.EditingElement).Text.Length;
}

You can use use ((TextBox)e.EditingElement).SelectionStart = 0; to place the cursor at the beginning of the original text of that cell.

  • Related