如何在不嵌入资源文件的情况下本地化WPF XAML中的文本

时间:2015-04-22 18:05:44

标签: c# wpf xaml

我正在尝试使用资源文件本地化WPF应用程序以支持不同的语言。我已将资源文件的构建操作设置为"资源"。我设法使用Resgen,ResourceManager和GetString()方法从.cs文件本地化字符串,但我无法使用XAML文件中的绑定来完成。我还在XAML文件中尝试了Resx扩展和静态资源,但它们似乎都不起作用。我不希望资源文件的构建操作是嵌入资源,因为它必须再次编译。您能否建议我如何本地化XAML中的文本,并将构建操作设置为"资源"对于资源文件或帮助我使用任何其他方法,以便资源不嵌入到应用程序中。 在此先感谢!!

<Window x:Class="MyApplication.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Button Name="btn1" Height="50" Width="150" Content="{Binding Source={StaticResource LocalizedStrings}, Path=MyResource.World}" />
        <Button Name="btn2" Height="50" Width="150" HorizontalAlignment="Left" VerticalAlignment="Top" />
    </Grid>
</Window>

背后的代码是:

namespace MyApplication
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            string strResourcesPath = "C:\\Program Files\\MyApplication\\MyApplication";
            InitializeComponent();
            CultureManager.UICulture = new CultureInfo("fr-FR");
            //ResourceManager resourceMgr = ResourceManager.CreateFileBasedResourceManager("NewResource", strResourcesPath, null);
            ResourceManager resourceMgr = ResourceManager.CreateFileBasedResourceManager("MyResource", strResourcesPath, null);
            string msg = resourceMgr.GetString("Hello");
            btn2.Content = msg;
        }
    }
}

LocalizedString.cs:

namespace MyApplication
{
    class LocalizedStrings
    {
        public LocalizedStrings()
        {
        }
        private static MyApplication.MyResource myresource = new MyApplication.MyResource();
        public MyApplication.MyResource MyResource { get { return myresource; } }
    }
}

的App.xaml:

<Application x:Class="MyApplication.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:MyApplication"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
         <local:LocalizedStrings xmlns:local ="clr-namespace:MyApplication" x:Key="LocalizedStrings"/>
    </Application.Resources>
</Application>

0 个答案:

没有答案