Accessing a Rescources.resx resource in XAML from VS?

Jesse Knott 686 Reputation points
2021-05-08T01:55:52.02+00:00

Hello, I've been using the resx file manager in VisualStudio for my resource strings. It will make localizing my app a lot easier if I go that route down the road.
Here's my problem though. I have written a static class and function I use to get the strings in the C# code, but I cannot access the strings in my XAML code.

I am looking for a way to set my XAML <Label Text="" /> fields, and a way to set default values when setting up <Style> tags.

I've tried this, but cant figure out how to make this work. This is the code I have been trying to get to work for my <Style> tags, but it should be the same process for the regular XAML files too.

<ResourceDictionary
                    x:Class="MyAPp.Themes.AppStyles"
                    xmlns="http://xamarin.com/schemas/2014/forms"
                    xmlns:resx="clr-namespace:BoomStick.Properties">

        <Style x:Key="DataLabel" TargetType="Label">
                 <Setter Property="Text" Value="{x:Static resx:Resources.errSerial}" />
        </Style>

</ResouceDictionary>

I get errors that Resources cant be found, or I try variations that just end up with nothing being displayed.

Can someone help me figure it out?
I have read in some articles that by doing this you make the app less capable of localization.

I guess I could move all of my strings to a <ResourceDictionary> of their own, I could then just localize the XAML file, and then use a switch/case to choose between the various XAML file options.

Cheers!

Here are the accessor functions I created in my MyApp.Services namespace, perhaps someone can benefit from them, or someone can recommend a better way to do it?

        /// <summary>
        /// Generate an object based collection for using in a control or array
        /// <summary>
        /// <param name="incoming">The name of the resource string.</param>
        /// <returns></returns>

        public static ObservableCollection<string> GetCSVArray(string incoming)
        {
            ObservableCollection<string> outputList = new ObservableCollection<string>();
            if (incoming?.Length < 1 || String.IsNullOrEmpty(incoming) || string.IsNullOrEmpty(GetStringResource(incoming)))
            {
                outputList.Add("Error");
            }
            else
            {
                outputList = new ObservableCollection<string>(GetStringResource(incoming).Split(','));
            }
            return outputList;
        }

        /// <summary>
        /// Initializes a new instance of the class.
        /// </summary>
        /// <param name="name"> Name of string to retrieve. </param>
        /// <returns> <see cref="string" /> from resources file. </returns>
        public static object GetObjectResource(string name)
        {
            try
            {
                if (string.IsNullOrEmpty(name))
                {
                    return "";
                }

                var temp = new System.Resources.ResourceManager(
                                            "BoomStick.Properties.Resources",
                                            typeof(App).GetTypeInfo().Assembly);
                return temp.GetObject(name, null);
            }
            catch (System.Resources.MissingManifestResourceException mmre)
            {
                DebugTools.LogException(mmre);
            }
            catch (Exception ex)
            {
                DebugTools.LogException(ex);
            }
            return null;
        }
Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,297 questions
{count} votes

Accepted answer
  1. JarvanZhang 23,951 Reputation points
    2021-05-14T06:33:12.373+00:00

    Hello,​

    Welcome to our Microsoft Q&A platform!

    get errors that Resources cant be found ... However I cannot access the string within the XAML code.

    Did you get the exception like Xamarin.Forms.Xaml.XamlParseException: 'Position 17:16. StaticResource not found for key xxx'? To accesss the Resouces value, please use res:Resources extension instead of DynamicResource or StaticResource.

    The defined string in the Resource file can be access in XAML as below.

       <Label Text="{x:Static res:Resources.TheContent}"/>  
    

    Please don't forget to specify the default culture in the AssemblyInfo.cs file.

    Best Regards,

    Jarvan Zhang


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


1 additional answer

Sort by: Most helpful
  1. Jesse Knott 686 Reputation points
    2021-05-13T16:34:39.773+00:00

    @JarvanZhang
    I'll have to take a closer look at the tutorial you linked.
    The problem I have been having is that while I can use my class I built to access the resources in my code. I have not been able to access the resources in the XAML code.

    Assuming that the RESX file has a string defined

    szHelloWorld  = "Hello world";  
    

    For instance I can do this

    somefile.cs

    var hello = StringTools.GetStringResource("szHelloWorld"); // hello now contains "Hello World"  
    

    However I cannot access the string within the XAML code.

    <Label Style="{DynamicResource DataLabel}" Text="{StaticResource resx:szHelloWorld}" /> <!-- this fails to populate-->  
    

    My next step I am considering trying is to make a converter that I can pass a parameter to that will return the string value that I am looking for, or just calling my static function from the XAML directly.
    I was just hoping there was a more direct, simple approach to access the strings within the resx file from the XAML code it's self.

    0 comments No comments