David Zomada
David Zomada

Reputation: 157

Access to string.xml Xamarin.Forms

I need to access to the string.xml on the Resources folder to made my multilingual app.

I'm trying to find a way to do it. It should be simple but I didn't find and answer. This is my string.xml:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<resources xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <string name="Text">Text</string>
</resources>

I need to set the property text to my button. I try this but it doesn't work.

<Button x:Name="btn" Text="@string/Text"/>

Also I need to set the property by programmability. Somo thing like:

btn.Text=Resources.GetString(Resource.String.Text);

How could I do it?

Thank you.

Upvotes: 0

Views: 1416

Answers (3)

Wendy Zang - MSFT
Wendy Zang - MSFT

Reputation: 10938

If you want to do that with Strings.xml on Android, get the text value from MainActivity and pass the text as parameter to the MainPage.

Create the different Strings.xml file for different language.

Default: values/Strings.xml

<?xml version="1.0" encoding="utf-8" ?>
<resources>
 <string name="app_name">Default</string>
 <string name="taskcancel">Cancel</string>
</resources>

Spanish: values-es/Strings.xml

<?xml version="1.0" encoding="utf-8" ?>
<resources>
 <string name="app_name">Spanish</string>
 <string name="taskcancel">Cancelar</string>
</resources>

MainActivity:

 public string STR { get; set; }
    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);

        Xamarin.Essentials.Platform.Init(this, savedInstanceState);
        global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
        STR = Resources.GetText(Resource.String.taskcancel);
        LoadApplication(new App(STR));
    }

App.xaml.cs:

   public App(string text)
    {
        InitializeComponent();

        MainPage = new MainPage(text);
    }

MainPage:

    public MainPage(string text)
    {
        InitializeComponent();
        label.Text = text; 
    }

Upvotes: 0

Divyesh
Divyesh

Reputation: 2393

There is no need to use resource file like this in xamarin.forms. Check this article this will help you:

  1. https://xamgirl.com/handle-multilingual-in-xamarin-forms-without-any-plugin/
  2. https://www.c-sharpcorner.com/article/xamarin-forms-multiligual/

What you have done, we normally follow in Xamarin.Android project not in Xamarin.Forms.

Upvotes: 1

Paswan Satyam
Paswan Satyam

Reputation: 1

yor string.xml file

<resources>
    <string name="app_name">My Application</string>
    <string name="Text">Text</string>
</resources>

then you can add a button in an XML file like-

<Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/Text" />

Upvotes: -1

Related Questions