Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a string in AppResources

I'm using LocalizedResources to get localization for my WP 8.1 app. But if I used a code like this:

protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
    string xyz = string.Empty;
    NavigationContext.QueryString.TryGetValue("znam", out xyz);
    tekstZnamenitosti.Text = AppResources.tekstTrsat;
}

then I would have to have many if statements to check for each znamenitost. Is there a way to use

tekstZnamenitosti.Text = AppResources.xyz;

where xyz is a string that I made before and in it is the value passed from a page which I navigated from.

like image 366
RidableCthulu Avatar asked Mar 20 '23 07:03

RidableCthulu


2 Answers

You can get the AppResources value using ResourceManager:

tekstZnamenitosti.Text = AppResources.ResourceManager.GetString("xyz");
like image 177
Chris Shao Avatar answered Mar 21 '23 21:03

Chris Shao


Just to extend Chris Shao's answer(+1) a little - maybe somebody find it usefull:

Create special class for your Resources:

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

In App.xaml add Key to resources:

<Application.Resources>
    <local:AppRes x:Key="Localized"/>
    // ... rest of the code.

Now you can easily use your Resources from code:

string fromResources = AppRes.PropertyName;

and in XAML:

<TextBlock Text="{Binding PropertyName, Source={StaticResource Localized}}" ...

One thing you have to do is once you add your Resource to Resources.resw, you have to add another line:

public static string NewPropertyName { get { return load.GetString(GetProperty()); } }
like image 30
Romasz Avatar answered Mar 21 '23 23:03

Romasz