0

我使用 TextChangedEventArgs 动态创建了一个文本框,以限制文本框仅输入数字和小数点。以下是c#中的代码

const char Delete = (char)8;
if (Char.IsDigit(e.KeyChar))
{
    e.Handled = false;
}
else if (e.KeyChar == Delete)
{
    e.Handled = false;
}
else if (e.KeyChar == '.')
{
    if (!(amt.Text.Contains(".")))
        e.Handled = false;
    else
    {
        e.Handled = true;
    }
}
else
{
    e.Handled = true;
}

但我不能在 wpf 中使用它。

我尝试使用 e.key 或 e.Text 更改代码。但是这两个都不可用。它显示以下错误您是否缺少程序集或指令。

请任何人帮助我。

4

1 回答 1

3
    // one solution for filtering characters in a textbox.       
    // this is the PreviewKeyDown handler for a textbox named tbNumerical
    // Need to add logic for cancelling repeated decimal point and minus sign
    // or possible notation like 1.23e2 == 123
    private void tbNumerical_PreviewKeyDown(object sender, KeyEventArgs e)
    {
        System.Windows.Input.Key k = e.Key;

        // to see the key enums displayed, use a textbox or label
        // someTextBox.Text = k.ToString();

        // filter out control keys, not all are used, add more as needed
       bool controlKeyIsDown = Keyboard.IsKeyDown(Key.LeftShift);      

        if (!controlKeyIsDown &&
            Key.D0 <= k && k <= Key.D9 ||
            Key.NumPad0 <= k && k <= Key.NumPad9 ||
            k == Key.OemMinus || k == Key.Subtract ||
            k == Key.Decimal || k == Key.OemPeriod)   // or OemComma for european decimal point

        else
        {
            e.Handled = true;

            // just a little sound effect for wrong key pressed
            System.Media.SystemSound ss = System.Media.SystemSounds.Beep;
            ss.Play();

        }
    }
于 2013-04-29T20:01:40.033 回答