【问题标题】:Changing Default "input is not in a correct format" Validation Error in RIA Services更改 RIA 服务中的默认“输入格式不正确”验证错误
【发布时间】:2011-11-07 04:15:52
【问题描述】:
当输入格式不正确时,我正在尝试更改 Silverlight DataGrid 中的默认错误消息。例如,您在数字字段中键入字母。当您离开时,它会显示“输入格式不正确”。我已经看到了如何解决这个问题,那就是在其上放置一个带有自定义错误消息的验证属性。问题是,我的对象来自 RIA 服务。它似乎忽略了我的验证属性中的自定义错误消息。我需要做些什么来揭露这个吗?提前致谢。
【问题讨论】:
标签:
silverlight
datagrid
wcf-ria-services
validationattribute
【解决方案1】:
验证属性/元数据属性在这里没有帮助,因为错误发生在控件上而不是属性上。
控件无法调用int(或任何其他数字类型)类型的设置器,因为无法转换字符串值。
我也想知道您可以更改默认错误消息...
一种可能的解决方法是使用只允许数字输入的自定义文本框,如下所示:
public class NumericTextBox : TextBox
{
public NumericTextBox()
{
this.KeyDown += new KeyEventHandler(NumericTextBox_KeyDown);
}
void NumericTextBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Back || e.Key == Key.Shift || e.Key == Key.Escape || e.Key == Key.Tab || e.Key == Key.Delete)
return;
if (e.Key < Key.D0 || e.Key > Key.D9)
{
if (e.Key < Key.NumPad0 || e.Key > Key.NumPad9)
{
e.Handled = true;
}
}
}
}
【解决方案3】:
唯一可行的解决方案是这个(这是在客户端):
public partial class MyEntity
{
public string MyField_string
{
get
{
return MyField.ToString();
}
set
{
decimal res = 0;
var b = Decimal.TryParse(value, out res);
if (!b)
throw new ArgumentException("Localized message");
else
this.MyField = Math.Round(res, 2);
}
}
partial void OnMyFieldChanged()
{
RaisePropertyChanged("MyField_string");
}
}
然后绑定到 MyField_string 而不是 MyField。