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

4

我正在开发一个WPF应用程序,用户可以在运行时更改语言(而不是当前区域设置!)。因此,我有多个类型为XAML的资源字典,其中添加了文本以使我的WPF应用程序支持多种语言:

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

我获得了"true",这意味着该键存在。 我该如何获取该键对应的值?
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个回答

15

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

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

来源


谢谢参数!你是对的。我已经搜索了两个小时,阅读了数十篇文章。 - Patrick Pirzer
1
我正在使用额外的ResourceDictionary,索引器也返回null。可能出了什么问题? - florien

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接