仅在DataGrid中输入数字 [英] numeric input only in DataGrid
问题描述
我正在尝试将特定列中的数据控制为仅数字形式,但是问题是DataGrid中没有KeyPressed事件。
我尝试使用KeyUp和KeyDown,但又遇到另一个问题:
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 I got another problem :
private void DG1_KeyDown(object sender, KeyEventArgs e)
{
float f;
if (!float.TryParse(((char)e.Key).ToString(),out f))
{
e.Handled = false;
}
}//casting returns an incorrect char value for example NumPad4 returns 'K'
推荐答案
代替监听特定键,更简单的方法是监听 TextBox
PreviewTextInput
事件。在此处内部,可以确定新文本是字母还是数字,然后正确处理。
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);
}
可以为每个DataGrid TextBox列进行设置。
This can be set up for each DataGrid TextBox column.
您可能需要手动设计DataGrid,以便更轻松地将事件与仅数字列关联。像这样的东西:
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>
这篇关于仅在DataGrid中输入数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!