2017-05-03 90 views
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方面不是很熟練......任何人都可以解釋我接下來的步驟是什麼?

回答

0

TranslationSource不是一個命名空間,它是一個類名

變化

xmlns:ns="clr-namespace:TranslationSource" 

xmlns:ns="clr-namespace:WpfApplication1" 

或相應的命名空間,你有TranslationSourceLocExtension