如何编辑resx文件(资源键值)运行时wpf c#

如何编辑resx文件(资源键值)运行时wpf c#,c#,wpf,resources,resx,C#,Wpf,Resources,Resx,我有一个多语言应用程序,用几种语言运行。在我的应用程序中,有用户可以更改的文本,但默认文本也需要翻译成不同的语言。这意味着,如果用户想要编辑某些文本,则需要为其语言编辑resx文件 首先我尝试使用ResourceWriter类,然后我的resx文件被破坏。我又创造了一次 其次,我尝试使用ResXResourceWriter类,但找不到提供此功能(编辑某些属性的值)的好方法 我想只需像xml一样读取resx文件并进行编辑,但我不知道如何使应用程序重新构建 是否可以在运行时从应用程序编辑resx中的

我有一个多语言应用程序,用几种语言运行。在我的应用程序中,有用户可以更改的文本,但默认文本也需要翻译成不同的语言。这意味着,如果用户想要编辑某些文本,则需要为其语言编辑resx文件

首先我尝试使用
ResourceWriter
类,然后我的resx文件被破坏。我又创造了一次

其次,我尝试使用
ResXResourceWriter
类,但找不到提供此功能(编辑某些属性的值)的好方法

我想只需像xml一样读取resx文件并进行编辑,但我不知道如何使应用程序重新构建

是否可以在运行时从应用程序编辑resx中的值。在这之后,就可以像visual studio中的内置代码一样使用c代码构建应用程序

编辑我不想将resx文件从.en.resx更改为其他文件(.de.resx)。我想更改此resx文件中的值。例如,我有一个键,该键与值Click相连接。我想将btnCont更改为具有新值,例如单击我。然后,再次为已更改的resx文件生成dll


感谢您的建议

也许有更好的方法可以做到这一点(我很想了解它们),但当我需要在运行时更改语言时,我要做的是将所有可本地化字符串作为只读属性添加到我的viewmodel中

    public string ImportString { get { return lang.Import; } }
    protected void NotifyAllPropertiesChanged<T>()
    {
        foreach (var p in this.GetType().GetProperties())
            if (p.PropertyType == typeof(T))
                OnPropertyChanged(p.Name);
    }
然后,我从XAML向这个字符串添加一个绑定,在更改UI区域性之后,我对viewmodel的所有字符串属性调用OnPropertyChanged

    public string ImportString { get { return lang.Import; } }
    protected void NotifyAllPropertiesChanged<T>()
    {
        foreach (var p in this.GetType().GetProperties())
            if (p.PropertyType == typeof(T))
                OnPropertyChanged(p.Name);
    }
受保护的void NotifyAllPropertiesChanged()
{
foreach(此.GetType().GetProperties()中的var p)
如果(p.PropertyType==typeof(T))
OnPropertyChanged(p.Name);
}

尝试编译以下代码

    <Window x:Class="WPFLocalizationSample.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>
    <StackPanel HorizontalAlignment="Left" Margin="20" VerticalAlignment="Top">
        <TextBlock Text="{DynamicResource tbName}" Margin="2" />
        <TextBox Width="200" Margin="2"/>
        <Button Content="{DynamicResource btnAdd}" HorizontalAlignment="Left" Margin="2" />
    </StackPanel>


    <StackPanel HorizontalAlignment="Left" Margin="20,181,0,0" VerticalAlignment="Top" Orientation="Vertical" Width="305">
        <TextBlock Text="Translation Panel" FontSize="20" FontWeight="Black" />
        <Grid >
            <TextBlock Text="{DynamicResource tbName}" Margin="2"  />
            <TextBox Width="200" Margin="2" HorizontalAlignment="Right" Tag="tbName"   x:Name="tbNameLoc"/>
        </Grid>
        <Grid>
            <TextBlock Text="{DynamicResource btnAdd}" Margin="2" />
            <TextBox Width="200" Margin="2" HorizontalAlignment="Right" Tag="btnAdd" x:Name="btnAddLoc" />
        </Grid>
        <Button Content="Translate/Update" HorizontalAlignment="Left" Margin="2" Click="Button_Click" />
    </StackPanel>
    </Grid>
  </Window>

这里是MainWindow.Xaml.cs

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Markup;

namespace WPFLocalizationSample
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    private static ResourceDictionary CurrentLanguageDictionary;
    private static string LanguageResourceFile = "en-US.xaml";
    private Dictionary<string, System.Windows.Controls.TextBox> TextBoxControls = new Dictionary<string, TextBox>();
    public MainWindow()
    {
        InitializeComponent();
        AddControlsToLocalization();
    }

    private void AddControlsToLocalization()
    {
        TextBoxControls.Add("tbName", tbNameLoc);
        TextBoxControls.Add("btnAdd", btnAddLoc);
    }

    public static bool SaveLanguageFile(Dictionary<string, System.Windows.Controls.TextBox> TextBoxControls, string selectedLang)
    {

        bool status = false;
        try
        {
            using (var fs = new FileStream(LanguageResourceFile, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                // Read in ResourceDictionary File
                CurrentLanguageDictionary = (ResourceDictionary)XamlReader.Load(fs);
            }

            foreach (string key in TextBoxControls.Keys)
            {
                TextBox txt = TextBoxControls[key];
                if (txt.Text.Length > 0)
                {
                    CurrentLanguageDictionary[key] = txt.Text;
                }
            }

            using (var writer = new StreamWriter(LanguageResourceFile))
            {
                XamlWriter.Save(CurrentLanguageDictionary, writer);
            }
            status = true;
        }
        catch (Exception _exception)
        {
            MessageBox.Show("Exception in language file edit");
            return false;
        }

        SetLanguageResourceDictionary(LanguageResourceFile, App.Current);

        return status;

    }
    public static void SetLanguageResourceDictionary(String inFile, Application application)
    {
        if (File.Exists(inFile))
        {
            // Read in ResourceDictionary File
            var languageDictionary = new ResourceDictionary();
            languageDictionary.Source = new Uri(inFile,UriKind.Relative);

            // Remove any previous Localization dictionaries loaded
            int langDictId = -1;
            for (int i = 0; i < application.Resources.MergedDictionaries.Count; i++)
            {
                var md = application.Resources.MergedDictionaries[i];
                // Make sure your Localization ResourceDictionarys have the ResourceDictionaryName
                // key and that it is set to a value starting with "Loc-".
                if (md.Contains("ResourceDictionaryName"))
                {
                    if (md["ResourceDictionaryName"].ToString().Equals("en-US"))
                    {
                        langDictId = i;
                        break;
                    }
                }
            }
            if (langDictId == -1)
            {
                // Add in newly loaded Resource Dictionary
                application.Resources.MergedDictionaries.Add(languageDictionary);
            }
            else
            {
                // Replace the current langage dictionary with the new one
                application.Resources.MergedDictionaries[langDictId] = languageDictionary;
            }
        }
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        SaveLanguageFile(TextBoxControls, "en-US");
    }
}
}
使用系统;
使用System.Collections.Generic;
使用System.IO;
使用System.Windows;
使用System.Windows.Controls;
使用System.Windows.Markup;
命名空间WPFLocalizationSample
{
/// 
///MainWindow.xaml的交互逻辑
/// 
公共部分类主窗口:窗口
{
私有静态资源字典CurrentLanguageDictionary;
私有静态字符串LanguageResourceFile=“en US.xaml”;
私有字典TextBoxControls=新字典();
公共主窗口()
{
初始化组件();
AddControlsToLocalization();
}
私有void AddControlsToLocalization()
{
添加(“tbName”,tbNameLoc);
添加(“btnAdd”,btnAddLoc);
}
公共静态bool savelanguage文件(字典textbox控件,字符串selectedLang)
{
布尔状态=假;
尝试
{
使用(var fs=new FileStream(LanguageResourceFile,FileMode.Open,FileAccess.Read,FileShare.Read))
{
//读入资源字典文件
CurrentLanguageDictionary=(ResourceDictionary)XamlReader.Load(fs);
}
foreach(TextBoxControls.Keys中的字符串键)
{
TextBox txt=TextBoxControls[key];
如果(txt.Text.Length>0)
{
CurrentLanguageDictionary[key]=txt.Text;
}
}
使用(var writer=newstreamwriter(LanguageResourceFile))
{
Save(CurrentLanguageDictionary,writer);
}
状态=真;
}
捕获(异常_异常)
{
MessageBox.Show(“语言文件编辑中的异常”);
返回false;
}
SetLanguageResourceDictionary(LanguageResourceFile,App.Current);
返回状态;
}
公共静态void SetLanguageResourceDictionary(字符串填充,应用程序)
{
如果(File.Exists(infle))
{
//读入资源字典文件
var languageDictionary=新资源字典();
languageDictionary.Source=新Uri(infle,UriKind.Relative);
//删除以前加载的所有本地化词典
int langdictd=-1;
for(int i=0;i
下面是示例en-US.xaml(资源字典文件)


恩美
输入您的姓名
添加
在app.xaml中添加资源文件

<Application x:Class="WPFLocalizationSample.App"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         StartupUri="MainWindow.xaml">
<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="en-US.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>
</Application>

如果编译这个,您将看到一个带有两个示例控件的表单。 下面添加了翻译面板。你可以输入任何你想要的文本