我有一个使用 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/