我正在尝试获得一个非常简单的控制台应用程序,以便在我的对象上使用本地化和 TryValidateObject。
我有一个学生类:
public class Student
{
[Display(ResourceType = typeof(Strings), Name = @"Student_Name_DisplayName")]
[Required]
public string Name {get; set;}
}
我的默认语言(英语)有一个公共(public)资源 Strings.resx
Key = Student_Name_DisplayName
Value = Name
我有一个西类牙语的内部资源文件 Strings.es.resx
Key = Student_Name_DisplayName
Value = Nombre
如果我创建了一个新的 Student 对象并且没有将 Name 属性设置为某物,我希望在调用 Validator.TryValidateObject 时看到错误。我愿意。
将当前 Culture 和 UI Culture 设置为英语,我得到验证错误: “名称字段是必需的。”
将当前文化和 UI 文化设置为西类牙语,我收到验证错误: “Nombre 字段是必需的。”
非常接近,但我希望消息的其余部分也使用西类牙语。
我发现在 Silverlight 中这样做是有效的 - Silveright 以某种方式“看到”正确的语言并为我提供正确的错误。但是,我有一些服务器端处理我也想返回正确的翻译字符串。
完整代码如下:
System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en");
System.Threading.Thread.CurrentThread.CurrentUICulture = new CultureInfo("en");
Student student = new Student();
var validationResults = new Collection<ValidationResult>();
Validator.TryValidateObject(student, new ValidationContext(student, null, null), validationResults, true);
if (validationResults.Count > 0)
Debug.WriteLine(validationResults[0].ErrorMessage);
//produces "The Name field is required"
validationResults.Clear();
System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("es");
System.Threading.Thread.CurrentThread.CurrentUICulture = new CultureInfo("es");
Student student2 = new Student();
Validator.TryValidateObject(student2, new ValidationContext(student2, null, null), validationResults, true);
if (validationResults.Count > 0)
Debug.WriteLine(validationResults[0].ErrorMessage);
//produces "The Nombre field is required"
想法?
谢谢(谢谢)
最佳答案
Silverlight 似乎附带了所有本地化资源,但 .NET 框架却没有。
尝试安装 .NET 语言包(对于 .NET 4.5:http://www.microsoft.com/en-us/download/details.aspx?id=30667)
关于C#/.Net TryValidateObject - 如何本地化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18642251/