简体   繁体   中英

How to get designtime text visible in a multi-language application in WPF?

I have a WPF application where I'm using resource files to make it multi-language.

Like this:

private void Application_Startup(object sender, StartupEventArgs e)
{
    try
    {
        var lang = new Uri("pack://siteoforigin:,,,/Languages/" + Settings.Default.Language + ".xaml", UriKind.RelativeOrAbsolute);
        this.Resources.MergedDictionaries.Add(new ResourceDictionary() { Source = lang });
    }
    catch
    {
        this.Resources.MergedDictionaries.Clear();
        this.Resources.MergedDictionaries.Add(new ResourceDictionary() { Source = new Uri("..\\Languages\\English.xaml", UriKind.RelativeOrAbsolute) });
    }
}

So, for any labels that display text, I set them like this:

<TextBlock Text="{DynamicResource DYouKnow}"/>

This works great at runtime but at design time I don't see my default text on my labels, which makes it difficult to design/maintain the UI.

Is there another way of doing this?

Using a MarkupExtension, you can create an extension you can use in your XAML which will provide design-time text as well.

You can use it as follows:

<TextBlock loc:TranslateExtension.Key="txtTextKey" Text="{loc:TranslateExtension Default='Default text'}" />

See the following tutorial: http://www.wpftutorial.net/localizemarkupextension.html

Try the following in your View constructor after the InitializeComponent() call:

if (DesignerProperties.GetIsInDesignMode(this))
     this.Resources.MergedDictionaries.Add(new ResourceDictionary() { Source = new Uri("..\\Languages\\English.xaml", UriKind.RelativeOrAbsolute) })

..with the XAML URI adjusted to the particular folder location of the current View file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM