You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将WPF TextBox输入限制为1-50或0-50的数值范围?

WPF TextBox 数值范围限制方案(1-50/0-50)

完全可行,给你两种实用的实现方式:

方法一:使用WPF原生ValidationRule(推荐)

这种方式符合WPF的MVVM设计思路,验证逻辑和UI解耦,还能直观显示错误提示。

  1. 自定义ValidationRule类:
public class NumberRangeValidationRule : ValidationRule
{
    public int Min { get; set; }
    public int Max { get; set; }

    public override ValidationResult Validate(object value, CultureInfo cultureInfo)
    {
        if (!int.TryParse(value.ToString(), out int number))
        {
            return new ValidationResult(false, "请输入有效数字");
        }

        if (number < Min || number > Max)
        {
            return new ValidationResult(false, $"请输入{Min}-{Max}之间的数值");
        }

        return ValidationResult.ValidResult;
    }
}
  1. 在XAML中引用这个验证规则:
<!-- 限制0-50的TextBox -->
<TextBox>
    <TextBox.Text>
        <Binding Path="YourProperty" UpdateSourceTrigger="PropertyChanged">
            <Binding.ValidationRules>
                <local:NumberRangeValidationRule Min="0" Max="50" ValidationStep="RawProposedValue"/>
            </Binding.ValidationRules>
        </Binding>
    </TextBox.Text>
</TextBox>

<!-- 限制1-50的TextBox -->
<TextBox>
    <TextBox.Text>
        <Binding Path="AnotherProperty" UpdateSourceTrigger="PropertyChanged">
            <Binding.ValidationRules>
                <local:NumberRangeValidationRule Min="1" Max="50" ValidationStep="RawProposedValue"/>
            </Binding.ValidationRules>
        </Binding>
    </TextBox.Text>
</TextBox>

如果输入不符合范围,TextBox会自动显示红框,也可以自定义错误提示样式。

方法二:结合事件处理(适合简单场景)

针对你之前用PreviewTextInput只能逐位验证的问题,可以配合LostFocus事件做整体校验:

  1. 先在PreviewTextInput限制只能输入数字:
private void NumberTextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
    // 只允许输入数字
    e.Handled = !Regex.IsMatch(e.Text, @"^\d$");
}
  1. 再在LostFocus事件里校验数值范围:
// 限制0-50的处理
private void ZeroToFiftyTextBox_LostFocus(object sender, RoutedEventArgs e)
{
    var textBox = sender as TextBox;
    if (int.TryParse(textBox.Text, out int num))
    {
        if (num < 0 || num > 50)
        {
            textBox.Text = "0"; // 不符合就重置为最小值,也可以弹提示
        }
    }
    else
    {
        textBox.Text = "0";
    }
}

// 限制1-50的处理
private void OneToFiftyTextBox_LostFocus(object sender, RoutedEventArgs e)
{
    var textBox = sender as TextBox;
    if (int.TryParse(textBox.Text, out int num))
    {
        if (num < 1 || num > 50)
        {
            textBox.Text = "1";
        }
    }
    else
    {
        textBox.Text = "1";
    }
}

这种方式简单直接,适合不需要MVVM的小项目。

另外,MaxLength属性只限制字符长度,没法控制数值范围,所以确实没用,不用纠结这个。

内容的提问来源于stack exchange,提问作者Jess Chan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 09:41:29