gpt4 book ai didi

c# - 如何以编程方式从 App.xaml 访问资源字符串?

转载 作者:太空狗 更新时间:2023-10-29 21:08:38 25 4
gpt4 key购买 nike

我想从 App.xaml 中的代码访问一些字符串,例如:

<Application.Resources>
<ai:TelemetryContext x:Key="ApplicationInsightsBootstrapper" xmlns:ai="using:Microsoft.ApplicationInsights"/>
<ResourceDictionary x:Key="rd">
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="GlobalStylesResourceDictionary.xaml"/>
</ResourceDictionary.MergedDictionaries>
<!-- Application-specific resources. -->
<x:String x:Key="AppName">Platypus</x:String>
<x:String x:Key="BingMapsNamespace">http://schemas.microsoft.com/search/local/ws/rest/v1</x:String>
</ResourceDictionary>
</Application.Resources>

我想以编程方式获取这些值,所以我编写了这个实用函数:

internal static String GetResourceString(String keyStr)
{
var resldr = new Windows.ApplicationModel.Resources.ResourceLoader();
return resldr.GetString(keyStr);
}

但如果失败,“在 Platypus.exe WinRT 信息中出现类型为‘System.Exception’的第一次机会异常:未找到 ResourceMap。

我以为我找到了问题的解决方案here ,据说这种做法已被弃用,我应该改为这样做:

internal static String GetResourceString(String keyStr)
{
try
{
//var resldr = new Windows.ApplicationModel.Resources.ResourceLoader();
//return resldr.GetString(keyStr);
var resldr = ResourceLoader.GetForCurrentView();
return resldr.GetString(keyStr);
}
catch (Exception ex)
{
Debug.WriteLine("Something wrong with the keyStr? Exception in GetResourceString(): {0}", ex.Message);
}
return String.Empty;
}

但这也行不通;我得到相同的旧“WinRT 信息:未找到 ResourceMap”。也使用此代码。

我传递的 arg 是有效的:

String bmn = GetResourceString("BingMapsNamespace");

那么问题是什么?

更新

使用 App.xaml.cs 而不是它的表亲可能同样好(或者更好,实际上,因为它可能会起作用):

public static string BingMapsNamespace { get; set; }
. . .
BingMapsNamespace = "http://schemas.microsoft.com/search/local/ws/rest/v1";

然后像这样从其他地方访问它:

String bmn = App.BingMapsNamespace;

后来:是的,它确实有效。我将另一个标记为正确,因为它显然对某些人有效。

最佳答案

这对我来说很好:

<Application.Resources>
<x:String x:Key="AppName">My App Name</x:String>
</Application.Resources>

然后在代码中:

string text = (string)App.Current.Resources["AppName"];

我不知道这样做是否正确,但它足够方便。 :)

关于c# - 如何以编程方式从 App.xaml 访问资源字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26558246/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com