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

标签 c# wpf mvvm

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

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

View 模型实现接口(interface) INotifyDataErrorInfo。

当我删除文本以输入新文本时,它显示“无法转换值”。

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

可以下载整个 Visual Studio 解决方案 here

最佳答案

提供自定义验证消息的最简单方法是实现 IDataErrorInfo Interface INotifyDataErrorInfo Interface在您的数据对象类中。这里不做详细的实现,因为网上很容易找到很多教程,不过,我会简单解释一下。

实现 IDataErrorInfo 时接口(interface),您有一个需要实现的索引器属性,它接受 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 时接口(interface),你用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"); } }
}

请在线搜索有关实现这些接口(interface)的更多信息。

关于c# - 在文本框中输入非数字时更改默认错误消息需要整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30755481/

相关文章:

c# - 如何在 MVC 3 中通过 jQuery 加载传递对象数组?

c# - STAThread 和多线程

c# - 如何在 .NET Core RC2 控制台应用程序(Linux、Debian 8)中使用 System.Data?

c# - ItemsControl 中使用的 WPF Expander 覆盖

c# - 更改 WPF 用户控件对另一个用户控件的可见性(登录)

wpf - 在 F# WPF MVVM 应用程序中绑定(bind)到 TextBox 的 TextChanged 事件

wpf - 如何使用 DataTrigger 启动 Storyboard ?

c# - 片段内的膨胀布局

wpf - 将 FlowDocument 转换为简单文本

c# - DataGrid 的 Columns 集合中已存在 header 为 '*' 的 DataGridColumn