1
我想在运行时更改绑定到资源文件的文本。更改绑定到资源文件的文本
对于我下面这个教程:
https://codinginfinity.me/post/2015-05-10/localization_of_a_wpf_app_the_simple_approach
我只是创建了一个WPF项目,新增2个资源文件,第一个命名Resource.resx,第二个命名Resource.pt-PT .resx,他们都有一个名为Tag1的字段。然后,我创建了在前面的教程中给出的代码的类:
namespace WpfApplication1
{
public class TranslationSource
: INotifyPropertyChanged
{
private static readonly TranslationSource instance = new TranslationSource();
public static TranslationSource Instance
{
get { return instance; }
}
private readonly ResourceManager resManager = Properties.Resources.ResourceManager;
private CultureInfo currentCulture = null;
public string this[string key]
{
get { return this.resManager.GetString(key, this.currentCulture); }
}
public CultureInfo CurrentCulture
{
get { return this.currentCulture; }
set
{
if (this.currentCulture != value)
{
this.currentCulture = value;
var @event = this.PropertyChanged;
if (@event != null)
{
@event.Invoke(this, new PropertyChangedEventArgs(string.Empty));
}
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
public class LocExtension
: Binding
{
public LocExtension(string name)
: base("[" + name + "]")
{
this.Mode = BindingMode.OneWay;
this.Source = TranslationSource.Instance;
}
}
}
最后创建了下面的XAML代码的简单接口:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ns="clr-namespace:TranslationSource"
Title="MainWindow" Height="350" Width="525">
<Grid>
<StackPanel Margin="10">
<Button Content="{x:Static ns:Loc Tag1}" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click"/>
</StackPanel>
</Grid>
</Window>
这是我的Button_Click事件做:
private void Button_Click(object sender, RoutedEventArgs e)
{
TranslationSource.Instance.CurrentCulture = new System.Globalization.CultureInfo("pt-PT");
}
我现在的问题是我的UI连接TranslationSource代码,教程错过的那部分,可能是因为它的东西很简单,但可惜的是我我在WPF方面不是很熟练......任何人都可以解释我接下来的步骤是什么?