我想从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。 ”
我以为我在这里找到了解决问题的方法,据说解决方法已经过时,我应该这样做:
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"];
我不知道这是否是正确的方法,但这很方便。:)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句