Numeric Data Entry in WPF

前端 未结 17 2540
情话喂你
情话喂你 2020-12-02 05:38

How are you handling the entry of numeric values in WPF applications?

Without a NumericUpDown control, I\'ve been using a TextBox and handling its PreviewKeyDown eve

17条回答
  •  [愿得一人]
    2020-12-02 06:10

    private void txtNumericValue_PreviewKeyDown(object sender, KeyEventArgs e)
    {
        KeyConverter converter = new KeyConverter();
    
        string key = converter.ConvertToString(e.Key);
    
        if (key != null && key.Length == 1)
        {
            e.Handled = Char.IsDigit(key[0]) == false;
        }
    }
    

    This is the easiest technique I've found to accomplish this. The down side is that the context menu of the TextBox still allows non-numerics via Paste. To resolve this quickly I simply added the attribute/property: ContextMenu="{x:Null}" to the TextBox thereby disabling it. Not ideal but for my scenario it will suffice.

    Obviously you could add a few more keys/chars in the test to include additional acceptable values (e.g. '.', '$' etc...)

提交回复
热议问题