我正試圖獲得一個非常簡單的控制檯應用程序,以便在本地對象上使用本地化和TryValidateObject。C#/ .Net TryValidateObject - 如何本地化?
我有一個學生類:
public class Student
{
[Display(ResourceType = typeof(Strings), Name = @"Student_Name_DisplayName")]
[Required]
public string Name {get; set;}
}
我有一個公共資源Strings.resx爲我的默認語言(英語)與
Key = Student_Name_DisplayName
Value = Name
我有一個內部的資源文件Strings.es。 RESX西班牙
Key = Student_Name_DisplayName
Value = Nombre
如果我創建一個新的Student對象,並且不將Name屬性設置一些事情,如果我調用Validator.TryValidateObject,我希望看到一個錯誤。我做。
將當前的文化和UI文化設置爲英文,出現驗證錯誤: 「名稱字段是必需的。」
將當前的Culture和UI文化設置爲西班牙語,出現驗證錯誤: 「The Nombre field is required。」
非常接近,但我希望留言的其他部分也用西班牙語。
我發現這樣做在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"
的思考?
感謝(格拉西亞斯)
就是這樣 - 我需要語言包,非常感謝! –