在AppResources中使用字符串
本文关键字:字符串 AppResources | 更新日期: 2023-09-27 18:08:59
我使用LocalizedResources
来为我的WP 8.1应用程序进行本地化。但是如果我使用这样的代码:
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
string xyz = string.Empty;
NavigationContext.QueryString.TryGetValue("znam", out xyz);
tekstZnamenitosti.Text = AppResources.tekstTrsat;
}
那么我必须有许多if语句来检查每个znamenitost
。有没有办法使用
tekstZnamenitosti.Text = AppResources.xyz;
其中xyz是我之前制作的字符串,其中是从我导航的页面传递的值。
AppResources
值可以通过ResourceManager:
tekstZnamenitosti.Text = AppResources.ResourceManager.GetString("xyz");
稍微扩展一下Chris Shao的答案(+1)——也许有人会觉得有用:
为资源创建特殊类:
namespace YourNamespace
{
public class AppRes
{
private static ResourceLoader load = new ResourceLoader();
private static string GetProperty([CallerMemberName] string propertyName = null) { return propertyName; }
public static string PropertyName { get { return load.GetString(GetProperty()); } }
}
}
在App.xaml中添加键到资源:
<Application.Resources>
<local:AppRes x:Key="Localized"/>
// ... rest of the code.
现在你可以很容易地使用你的资源从代码:
string fromResources = AppRes.PropertyName;
和在XAML中:
<TextBlock Text="{Binding PropertyName, Source={StaticResource Localized}}" ...
你必须做的一件事是,一旦你将资源添加到资源中。对于,您必须添加另一行:
public static string NewPropertyName { get { return load.GetString(GetProperty()); } }
是的,您可以在App.xaml.cs
中设置字符串值,例如
public static string xyz;
然后你可以将你想要的值保存到你在App.xaml.cs中创建的变量中。
tekstZnamenitosti.Text = App.xyx;
你可以在应用的任何地方使用这个变量。