您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

我如何获得一个TextBox只接受WPF中的数字输入?

我如何获得一个TextBox只接受WPF中的数字输入?

添加预览文本输入事件。像这样:<Text@R_421_2419@ PreviewTextInput="PreviewTextInput" />

然后在该设置内,e.Handled如果不允许输入文本。e.Handled = !IsTextAllowed(e.Text);

我在IsTextAllowed方法中使用了一个简单的正则表达式,以查看是否应该允许他们键入内容。就我而言,我只想允许数字,点和破折号。

private static readonly Regex _regex = new Regex("[^0-9.-]+"); //regex that matches disallowed text
private static bool IsTextAllowed(string text)
{
    return !_regex.IsMatch(text);
}

如果你想防止不正确的数据勾起来了的粘贴DataObject.Pasting事件DataObject.Pasting="Text@R_421_2419@Pasting"在这里代码摘录):

// Use the DataObject.Pasting Handler 
private void Text@R_421_2419@Pasting(object sender, DataObjectPastingEventArgs e)
{
    if (e.DataObject.GetDataPresent(typeof(String)))
    {
        String text = (String)e.DataObject.GetData(typeof(String));
        if (!IsTextAllowed(text))
        {
            e.CancelCommand();
        }
    }
    else
    {
        e.CancelCommand();
    }
}
其他 2022/1/1 18:16:10 有431人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶