如何从C#中的资源字典(XAML)中获取值

时间:2017-02-01 14:08:41

标签: 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>

WPF窗口和控件受窗口资源的约束。 但我正在使用DataAnnotations进行验证。 我的第一个想法是在我的viewmodel中验证时将文本提供给键“insert_first_name”。 所以我试图通过使用它来获得它:

System.Windows.Application.Current.Resources.FindName("insert_first_name")

但是当我使用FindName方法时,我得到null。

当我尝试

System.Windows.Application.Current.Resources.Contains("insert_first_name")

我得到“真实”,这意味着密钥存在。

如何获得键值?

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");
}

1 个答案:

答案 0 :(得分:7)

要从代码中查找应用程序范围的资源,请使用Application.Current.Resources获取应用程序的资源字典,如下所示:

string insertFirstName = Application.Current.Resources["insert_first_name"];

Source