Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 782
Bjorn Fontaine Avatar asked Feb 18 '18 14:02

Bjorn Fontaine


People also ask

What is dynamic resource in Xamarin forms?

The DynamicResource markup extension is similar to the StaticResource markup extension in that both use a dictionary key to fetch a value from a ResourceDictionary . However, while the StaticResource performs a single dictionary lookup, the DynamicResource maintains a link to the dictionary key.


2 Answers

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.

like image 121
Martin Zikmund Avatar answered Oct 12 '22 17:10

Martin Zikmund


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.

like image 23
C. Carter Avatar answered Oct 12 '22 16:10

C. Carter