更改在文本框中输入非数字需要整数时的默认错误消息

本文关键字:整数 默认 消息 错误 数字 文本 输入 | 更新日期: 2023-09-27 17:54:48

我有一个使用MVVM的WPF应用程序。它有一个文本框,需要一个整数。该文本框的XAML如下

<TextBox Name="textBoxElementWeight" 
    Text="{Binding ElementName=listBoxElement, Path=SelectedItem.Weight,
    UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
    Validation.ErrorTemplate="{StaticResource ValidationTextBoxTemplate}"/>

视图模型实现接口INotifyDataErrorInfo

当我删除文本输入一个新的,它说"值"无法转换。

如何将此错误信息更改为我的错误信息?例如:"请输入一个数字。"

完整的Visual Studio解决方案可以在这里下载

更改在文本框中输入非数字需要整数时的默认错误消息

提供自定义验证消息的最简单方法是在数据对象类中实现IDataErrorInfo接口或INotifyDataErrorInfo接口。我不会在这里详细介绍实现,因为在网上很容易找到许多教程,但是,我将简要解释。

当实现IDataErrorInfo接口,你有一个索引器属性,你需要实现在string属性名称。它可以这样使用:

public override string this[string propertyName]
{
    get
    {
        string error = string.Empty;
        if (propertyName == "Name" && Name.IsNullOrEmpty()) error = "You must enter the Name field.";
        else if (propertyName == "Name" && Name.Length > 100) error = "That name is too long.";
        ...
        return error;
    }
}

实现INotifyDataErrorInfo接口时,在每个属性上使用DataAnnotation属性,如下所示:

[Required(ErrorMessage = "You must enter the Name field.")]
[StringLength(100, ErrorMessage = "That name is too long.")]
public string Name
{
    get { return name; }
    set { if (value != name) { name = value; NotifyPropertyChanged("Name", "Errors"); } }
}

请上网查询有关实现这些接口的更多信息。