仅在 DataGrid 中输入数字

numeric input only in DataGrid

我正在尝试将特定列中的数据控制为仅为数字,但问题是 DataGrid 中没有 KeyPressed 事件。 我尝试使用 KeyUp 和 KeyDown 但我遇到了另一个问题:

        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 事件。在这里,你可以判断新文本是字母还是数字,然后正确处理。

private void OnPreviewTextInput(object sender, TextCompositionEventArgs e)
{
    e.Handled = new Regex("[^0-9]+").IsMatch(e.Text);
}

这可以为每个 DataGrid 文本框列设置。

您可能需要手动设计 DataGrid,以便更轻松地将事件与仅数字列相关联。类似于:

<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>