【WPF】NumericUpDown的用法

在 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 中引用命名空间

cs 复制代码
<Window xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit"
        ...

3. 使用 NumericUpDown 控件

cs 复制代码
<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

示例结构:

cs 复制代码
<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.FormsNumericUpDown(不推荐)

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

数据绑定示例(MVVM)

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

cs 复制代码
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 绑定:

cs 复制代码
<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 接口:

cs 复制代码
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 中配置绑定以启用验证:

cs 复制代码
<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 方法中抛出异常的情况。

示例代码:

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

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

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

cs 复制代码
<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 及以上版本)。

相关推荐
mingupup2 小时前
WPF/C#:使用Microsoft Agent Framework框架创建一个带有审批功能的终端Agent
c#·wpf
△曉風殘月〆5 小时前
WPF中的变换(Transform)功能详解
wpf
mingupup6 小时前
为WPF应用增加项目图标
wpf
张人玉9 小时前
c#WPF基础知识
开发语言·c#·wpf
yantuguiguziPGJ18 小时前
WPF 联合 Web 开发调试流程梳理(基于 Microsoft.Web.WebView2)
前端·microsoft·wpf
Aevget18 小时前
DevExpress WPF中文教程:Data Grid - 如何使用虚拟源?(二)
.net·wpf·界面控件·devexpress·ui开发·数据网格
大美B端工场-B端系统美颜师1 天前
工控软件开发选择难?Electron、Qt、WPF 对比
qt·electron·wpf
c#上位机1 天前
MefBootstrapper在Prism引导程序中的使用
c#·wpf·prism
没有bug.的程序员2 天前
服务治理与 API 网关:微服务流量管理的艺术
java·分布式·微服务·架构·wpf
Brianna Home2 天前
【案例实战】鸿蒙分布式调度:跨设备协同实战
华为·wpf·harmonyos