仅允许WPF文本框中的数字输入

Jie*_*eng 13 c# validation wpf mvvm

我想验证用户输入以确保它们是整数.我该怎么做?我想到使用IDataErrorInfo哪种似乎是在WPF中进行验证的"正确"方法.所以我尝试在我的ViewModel中实现它.

但事情是我的文本框绑定到一个整数字段,并且没有任何需要验证是否int是一个int.我注意到WPF会自动在文本框周围添加一个红色边框,以通知用户错误.基础属性不会更改为无效值.但我想通知用户这个.我该怎么做?

Mag*_*son 14

另一种方法是简单地不允许非整数的值.以下实现有点糟糕,我想稍后对其进行抽象,以使其更具可重用性,但这就是我所做的:

在我的视图后面的代码中(我知道如果你是一个硬核mvvm可能会受伤; o))我定义了以下函数:

  private void NumericOnly(System.Object sender, System.Windows.Input.TextCompositionEventArgs e)
{
    e.Handled = IsTextNumeric(e.Text);

}


private static bool IsTextNumeric(string str)
{
    System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex("[^0-9]");
    return reg.IsMatch(str);

}
Run Code Online (Sandbox Code Playgroud)

在XAML视图中,每个只应该接受整数的文本框都是这样定义的:

   <TextBox Padding="2"  TextAlignment="Right" PreviewTextInput="NumericOnly" Text="{Binding xxx.yyyy}" MaxLength="1" />
Run Code Online (Sandbox Code Playgroud)

关键属性是PreviewTextInput

  • 这不会处理空格.我怎么处理dem? (2认同)

And*_*ana 12

您看到的红色边框实际上是ValidationTemplate,您可以扩展并为用户添加信息.看这个例子:

    <UserControl.Resources>
        <ControlTemplate x:Key="validationTemplate">
            <Grid>
                <Label Foreground="Red" HorizontalAlignment="Right" VerticalAlignment="Center">Please insert a integer</Label>
                <Border BorderThickness="1" BorderBrush="Red">
                    <AdornedElementPlaceholder />
                </Border>
            </Grid>
        </ControlTemplate>
    </UserControl.Resources>

<TextBox Name="tbValue" Validation.ErrorTemplate="{StaticResource validationTemplate}">
Run Code Online (Sandbox Code Playgroud)


kum*_*raw 8

我们可以对文本框更改事件进行验证.以下实现可防止除数字和一个小数点以外的按键输入.

private void textBoxNumeric_TextChanged(object sender, TextChangedEventArgs e)
{
        TextBox textBox = sender as TextBox;
        Int32 selectionStart = textBox.SelectionStart;
        Int32 selectionLength = textBox.SelectionLength;
        String newText = String.Empty;
        int count = 0;
        foreach (Char c in textBox.Text.ToCharArray())
        {
            if (Char.IsDigit(c) || Char.IsControl(c) || (c == '.' && count == 0))
            {
                newText += c;
                if (c == '.')
                    count += 1;
            }
        }
        textBox.Text = newText;
        textBox.SelectionStart = selectionStart <= textBox.Text.Length ? selectionStart : textBox.Text.Length;    
}
Run Code Online (Sandbox Code Playgroud)