How do I insert text at caret position in DataGridTextColumn when the user press Alt+X?
This is the DataGrid
<DataGrid x:Name="TheGrid" SelectionUnit="Cell" ItemsSource="{Binding Soruce}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Path=Value, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
</DataGrid.Columns>
</DataGrid>
I have tried a to make my own CellEditingTemplate and CellTemplate. But when I do it like that it messes up the Tab-functionality of the grid. I have to double or tripple-tab to edit the next cell.
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<TextBox Text="{Binding Path=Value, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" KeyDown="TextBox_KeyDown"></TextBox>
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=Value}"></TextBlock>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
Code behind. You cannot insert the text in directly to the databound model since you have to know the caret position.
private void TextBox_KeyDown(object sender, KeyEventArgs e)
{
//Insert text at caret position
}
Add a style that adds an EventSetter on the EditingElementStyle for the KeyDown-event.
<DataGrid x:Name="TheGrid" SelectionUnit="Cell" ItemsSource="{Binding Soruce}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Path=Value, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
<DataGridTextColumn.EditingElementStyle>
<Style TargetType="{x:Type TextBox}">
<EventSetter Event="KeyDown" Handler="TextBox_KeyDown" />
</Style>
</DataGridTextColumn.EditingElementStyle>
</DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
Then add the event handler to the code behind. Insert the text on the SelectedText porperty to get familiar behaviour and then move the carret to after the inserted text.
private void TextBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.SystemKey == Key.X && Keyboard.Modifiers.HasFlag(ModifierKeys.Alt))
{
string text = "Text to insert";
TextBox textBox = sender as TextBox;
textBox.SelectedText = text;
textBox.SelectionStart = textBox.SelectionStart + text.Length;
textBox.SelectionLength = 0;
}
}