【WPF】NumericUpDown的用法

发布于:2025-07-28 ⋅ 阅读:(19) ⋅ 点赞:(0)

在 WPF(Windows Presentation Foundation)中,NumericUpDown 控件并不是内置的标准控件之一,但它是一个非常常用的控件,用于让用户输入一个数值(整数或浮点数),并提供上下箭头来递增或递减数值。

在 WPF 中,你可以通过以下几种方式来使用 NumericUpDown 控件:

方法一:使用 Xceed WPF Toolkit 中的 NumericUpDown

这是最常见和推荐的方式,Xceed 提供了一个强大的 WPF 工具包,其中就包含 NumericUpDown

1. 安装 Xceed WPF Toolkit

使用 NuGet 安装:Install-Package Extended.Wpf.Toolkit

或者通过 Visual Studio 的 NuGet 包管理器搜索安装:Extended.Wpf.Toolkit

2. 在 XAML 中引用命名空间

<Window xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit"
        ...

3. 使用 NumericUpDown 控件

<xctk:NumericUpDown Name="numericUpDown1"
                    Minimum="0"
                    Maximum="100"
                    Value="50"
                    Increment="1"
                    ShowButtonSpinner="True"
                    FormatString="N0" />

4. 常用属性说明:

属性名 说明
Value 当前的数值(绑定用)
Minimum 最小值
Maximum 最大值
Increment 每次递增/递减的步长
ShowButtonSpinner 是否显示上下箭头按钮(默认为 true)
FormatString 显示格式,例如 N0 表示整数,F2 表示两位小数

 

方法二:使用自定义 UserControl 实现 NumericUpDown

如果你不想使用第三方库,也可以自己创建一个 UserControl,包含一个 TextBox 和两个 Button(↑ ↓)来模拟 NumericUpDown

示例结构:

<StackPanel Orientation="Horizontal">
    <TextBox Text="{Binding Value, UpdateSourceTrigger=PropertyChanged}" Width="50"/>
    <StackPanel Orientation="Vertical">
        <Button Content="▲" Click="ButtonUp_Click" />
        <Button Content="▼" Click="ButtonDown_Click" />
    </StackPanel>
</StackPanel>

然后在后台代码或 ViewModel 中处理数值的加减逻辑。

 

方法三:使用 System.Windows.Forms 的 NumericUpDown(不推荐)

WPF 可以通过 WindowsFormsIntegration 使用 WinForm 控件,但不推荐,因为会引入混合技术栈,维护麻烦。

数据绑定示例(MVVM)

如果你使用 MVVM 模式,可以在 ViewModel 中定义属性:

public class MainViewModel : INotifyPropertyChanged
{
    private decimal _value = 50;
    public decimal Value
    {
        get => _value;
        set
        {
            if (_value != value)
            {
                _value = value;
                OnPropertyChanged();
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged([CallerMemberName] string name = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
    }
}

XAML 绑定:

<xctk:NumericUpDown Value="{Binding Value}" Minimum="0" Maximum="100" />

注意事项

  • NumericUpDown 支持 decimal 类型,可以处理浮点数。
  • 支持格式化显示,比如货币、百分比等。
  • 推荐使用 Xceed 的版本,功能强大且易于维护。

 

DataValidation的用法

高级功能(比如小数位数限制、负数禁用、事件处理等),可以进一步扩展或使用 DataValidation 

DataValidation 在 WPF 中主要用于确保用户输入的数据符合应用程序的预期格式和范围。通过数据验证,可以在用户输入非法数据时提供即时反馈,提升用户体验。WPF 提供了几种方法来实现数据验证功能,其中最常用的是使用 IDataErrorInfo 接口和 ExceptionValidationRule 类。

以下是两种主要的数据验证方法:

1. 使用 IDataErrorInfo 实现数据验证

IDataErrorInfo 是一个接口,可以让你在 ViewModel 或 Model 中定义属性验证逻辑。当绑定到一个实现了 IDataErrorInfo 的对象时,WPF 会自动调用这个接口的方法来获取错误信息,并显示给用户。

示例代码:

首先,确保你的 ViewModel 实现了 IDataErrorInfo 接口:

public class MainViewModel : INotifyPropertyChanged, IDataErrorInfo
{
    private decimal _value;
    public decimal Value
    {
        get => _value;
        set
        {
            if (_value != value)
            {
                _value = value;
                OnPropertyChanged();
            }
        }
    }

    public string Error => null;

    public string this[string columnName]
    {
        get
        {
            if (columnName == nameof(Value))
            {
                if (Value < 0 || Value > 100)
                {
                    return "数值必须在0到100之间";
                }
            }
            return null;
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged([CallerMemberName] string name = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
    }
}

然后,在 XAML 中配置绑定以启用验证:

<Window x:Class="YourNamespace.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <xctk:NumericUpDown Value="{Binding Value, ValidatesOnDataErrors=True, NotifyOnValidationError=True}" Minimum="0" Maximum="100" />
    </Grid>
</Window>

注意:ValidatesOnDataErrors=TrueNotifyOnValidationError=True 需要设置以启用数据验证。

2. 使用 ExceptionValidationRule 实现数据验证

另一种方式是使用 ExceptionValidationRule 来处理异常情况作为验证错误。这种方式适用于你希望直接从属性 setter 方法中抛出异常的情况。

示例代码:

假设我们有一个简单的属性验证逻辑,它会在不满足条件时抛出异常:

private decimal _value;
public decimal Value
{
    get => _value;
    set
    {
        if (value < 0 || value > 100)
        {
            throw new ArgumentException("数值必须在0到100之间");
        }
        _value = value;
        OnPropertyChanged();
    }
}

 接下来,在 XAML 中配置绑定以使用 ExceptionValidationRule

<xctk:NumericUpDown Value="{Binding Value}">
    <xctk:NumericUpDown.BindingGroup>
        <BindingGroup>
            <BindingGroup.ValidationRules>
                <ExceptionValidationRule/>
            </BindingGroup.ValidationRules>
        </BindingGroup>
    </xctk:NumericUpDown.BindingGroup>
</xctk:NumericUpDown>

总结

  • IDataErrorInfo 是一种灵活且易于管理的数据验证方法,特别适合于 MVVM 模式。
  • ExceptionValidationRule 更加直接,但不如 IDataErrorInfo 灵活,通常用于需要抛出异常的场景。

根据你的需求选择合适的数据验证策略。如果你正在使用 MVVM 模式,推荐使用 IDataErrorInfo。如果需要更复杂的验证逻辑或跨字段验证,可能还需要考虑其他技术如 INotifyDataErrorInfo(适用于 .NET Framework 4.5 及以上版本)。

 


网站公告

今日签到

点亮在社区的每一天
去签到