I\'am trying to control the data in specific columns to be numeric only but the problem is there is no KeyPressed event in the DataGrid. I tried using KeyUp and KeyDown but
Instead of listening for specific keys, the easier route is to listen to the TextBox PreviewTextInput event. Inside here, you can determine whether the new text is alpha or numeric, and then handle it correctly.
private void OnPreviewTextInput(object sender, TextCompositionEventArgs e)
{
e.Handled = new Regex("[^0-9]+").IsMatch(e.Text);
}
This can be set up for each DataGrid TextBox column.
You may need to design the DataGrid manually so that it is easier to associate the event with the numeric only column. Something like:
<DataGrid ItemsSource="{Binding MyItems}" AutoGenerateColumns="False" >
<DataGrid.Columns>
<DataGridTemplateColumn Header="NumericOnly">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBox Text="{Binding Number}" PreviewTextInput="OnPreviewTextInput" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>