仅在DataGrid中输入数字

Con*_*nst 2 c# wpf 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'
Run Code Online (Sandbox Code Playgroud)

d.m*_*ada 5

而不是监听特定的键,更容易的途径是听取TextBox PreviewTextInput事件.在这里,您可以确定新文本是alpha还是数字,然后正确处理.

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

这可以为每个DataGrid TextBox列设置.

您可能需要手动设计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>
Run Code Online (Sandbox Code Playgroud)