Pat*_*zer 2 c# wpf xaml dictionary
我正在开发一个WPF应用程序,用户可以在运行时更改语言(而不是当前的文化!).所以我有多个XAML类型的资源字典,我添加了文本,使我的WPF-app多语言像这样:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:system="clr-namespace:System;assembly=mscorlib"
xmlns:local="clr-namespace:Validation_DataAnnotations2.Resources">
<system:String x:Key="firstname">First name</system:String>
<system:String x:Key="lastname">Last name</system:String>
<system:String x:Key="mainwindowtitle">Validation with DataAnnotations</system:String>
<system:String x:Key="german_language">German</system:String>
<system:String x:Key="english_language">English</system:String>
<system:String x:Key="insert_first_name">The first name has to be inserted</system:String>
</ResourceDictionary>
Run Code Online (Sandbox Code Playgroud)
WPF窗口和控件受窗口资源的约束.但我正在使用DataAnnotations进行验证.我的第一个想法是在我的viewmodel中验证时将文本提供给键"insert_first_name".所以我试图通过使用它来获得它:
System.Windows.Application.Current.Resources.FindName("insert_first_name")
Run Code Online (Sandbox Code Playgroud)
但是当我使用FindName方法时,我得到null.
当我尝试
System.Windows.Application.Current.Resources.Contains("insert_first_name")
Run Code Online (Sandbox Code Playgroud)
我得到"真实",这意味着密钥存在.
我怎样才能获得钥匙的价值?
protected void ValidateModel()
{
validationErrors.Clear();
ICollection<ValidationResult> validationResults = new List<ValidationResult>();
ValidationContext validationContext = new ValidationContext(personmodel, null, null);
if (!Validator.TryValidateObject(personmodel, validationContext, validationResults, true))
{
foreach (ValidationResult validationResult in validationResults)
{
string property = validationResult.MemberNames.ElementAt(0);
if (validationErrors.ContainsKey(property))
{
validationErrors[property].Add(validationResult.ErrorMessage);
}
else
{
validationErrors.Add(property, new List<string> { validationResult.ErrorMessage });
if (validationResult.ErrorMessage == "insert_first_name")
{
var text = System.Windows.Application.Current.Resources.FindName("insert_first_name");
}
}
}
}
// Raises the ErrorsChanged for all properties explicitly.
RaiseErrorsChanged("FirstName");
RaiseErrorsChanged("LastName");
}
Run Code Online (Sandbox Code Playgroud)
要从代码中查找应用程序范围的资源,请使用Application.Current.Resources获取应用程序的资源字典,如下所示:
string insertFirstName = Application.Current.Resources["insert_first_name"];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4814 次 |
| 最近记录: |