#1,134 – Localization XV – Localizing Other Content

You’ll sometimes have content in an application that needs to be localized but is not already present in a XAML file.  Below, a MessageBox uses a hard-coded string.

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            string message = "Apples are crunchy, portable and taste great!";
            MessageBox.Show(message, "Apples");
        }

One approach to this is to move the string into a XAML file as a resource and then localize the string when localizing all of the other content in the XAML file.

We start by including an XML namespace that defines an alias for the System namespace.

        xmlns:sys="clr-namespace:System;assembly=mscorlib"

We can now add the string as a resource (e.g. within a <Window> element).

    <Window.Resources>
        <sys:String x:Uid="sys:String_1" x:Key="AppleMessage">Apples are crunchy, portable and taste great!</sys:String>
    </Window.Resources>

At run-time, we can load the resource rather than a hard-coded string.

            string message = (string)this.Resources["AppleMessage"];
            MessageBox.Show(message, "Apples");