numeric input only in DataGrid

后端 未结 1 1960
猫巷女王i
猫巷女王i 2021-01-03 11:15

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

相关标签:
1条回答
  • 2021-01-03 11:44

    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>
    
    0 讨论(0)
提交回复
热议问题