设置光标位置,选择文本

问题描述:

喜不知道如何把光标DatagridCell内部,选择所有文字设置光标位置,选择文本

代码波纹管将焦点设置在小区,开始编辑。但光标不在单元格内,因此用户无法开始输入文字。此外,未选择,因此用户必须手动选择文本,而不是直接替换值。

Mainwindow.xaml.cs:

private void GrdLignes_SelectionChanged(object sender, SelectionChangedEventArgs e) 
    { 
     foreach (var c in GrdLignes.SelectedCells) 
     { 
      if (c.Column.Header.ToString() == "Quantité Livrée") 
      { 
       var cellContent = c.Column.GetCellContent(c.Item); 
       if (cellContent != null) 
       { 
        var dc = (DataGridCell)cellContent.Parent; 
        dc.Focus(); 
        dc.IsEditing = true; 
       } 
      } 
     } 
    } 

enter image description here

编辑:我说的光标=闪烁的插入符

你需要等待,直到在细胞中TextBlock已被替换为TextBox

定义一个EditingElementStyle和处理Loaded事件为TextBox

<DataGrid x:Name="GridLignes" ...> 
    <DataGrid.Resources> 
     <Style x:Key="tbStyle" TargetType="TextBox"> 
      <EventSetter Event="Loaded" Handler="OnLoaded" /> 
     </Style> 
    </DataGrid.Resources> 
    <DataGrid.Columns> 
     <DataGridTextColumn Header="Quantité Livrée" Binding="{Binding Qty}" EditingElementStyle="{StaticResource tbStyle}" /> 
     ... 
    </DataGrid.Columns> 
</DataGrid> 

private void OnLoaded(object sender, RoutedEventArgs e) 
{ 
    TextBox textBox = sender as TextBox; 
    Keyboard.Focus(textBox); 
    textBox.CaretIndex = textBox.Text.Length; 
    textBox.SelectAll(); 
} 
+0

这是工作!谢谢! – ebelair