Bjorn Fontaine
Bjorn Fontaine

Reputation: 464

Using Resource files in XAML in Xamarin.Forms

I'm trying to use a resource file in my XAML. For some reason i keep getting the error of not finding the type Texts. Not sure what I'm doing wrong here.

XAML

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:CashRegisterApp.Resources"
             x:Class="CashRegisterApp.Start">
    <ContentPage.Content>
        <StackLayout
            VerticalOptions="CenterAndExpand" 
                HorizontalOptions="CenterAndExpand" >
        <Label Text="{x:Static local:Texts.Start}"/>
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

RESX

resx file

Solution explorer

solution explorer

Upvotes: 9

Views: 6926

Answers (2)

C. Carter
C. Carter

Reputation: 291

I had this issue too and I hope this answer helps people in the future with this issue.

Following this guide taught me how to set up resx files in Xamarin forms. Their TranslateExtension allows for referring to the resx file directly from Xaml.

Unfortunately, in its raw form it doesn't pick up a runtime change in locales. This is fixable by changing their "Localize" class (on the native platforms) to keep a reference of the CultureInfo when changed via the SetLocale method and return it when the GetCurrentCultureInfo method is called.

Upvotes: 1

Martin Zikmund
Martin Zikmund

Reputation: 39102

Creating RESX files within Shared projects is known to cause issues. You can see several lengthy posts in Xamarin Forums regarding this (here and here for example).

The easiest solution that will allow you to use the approach you want is to create a new .NET Standard Library of PCL library in your solution, create your RESX files there and set their visibility to public. Then you will be able to utilize them using the x:Static syntax as expected.

Many developers use an alternative in the form of a custom markup extension like the solution by ClaudioPereira in this forum. This simplifies the syntax even more.

Finally, for most detailed information on Xamarin.Forms you can refer to the official documentation.

Upvotes: 11

Related Questions