2010-03-30 7 views
0

Je tente d'écrire une application multilingue dans Silverlight 4.0 et I au point où je peux commencer à remplacer mon texte statique par du texte dynamique provenant d'un fichier xaml SampleData. Voici ce que j'ai:Définir de manière dynamique la liaison de texte de TextBlock

Ma base de données

<SampleData:something xmlns:SampleData="clr-namespace:Expression.Blend.SampleData.MyDatabase" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"> 
    <SampleData:something.mysystemCollection> 
    <SampleData:mysystem ID="1" English="Menu" German="Menü" French="Menu" Spanish="Menú" Swedish="Meny" Italian="Menu" Dutch="Menu" /> 
    </SampleData:something.mysystemCollection> 
</SampleData:something> 

Mon UserControl

<UserControl 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" 
    x:Class="Something.MyUC" d:DesignWidth="1000" d:DesignHeight="600"> 
    <Grid x:Name="LayoutRoot" DataContext="{Binding Source={StaticResource MyDatabase}}"> 
     <Grid Height="50" Margin="8,20,8,0" VerticalAlignment="Top" d:DataContext="{Binding mysystemCollection[1]}" x:Name="gTitle"> 
      <TextBlock x:Name="Title" Text="{Binding English}" TextWrapping="Wrap" Foreground="#FF00A33D" TextAlignment="Center" FontSize="22"/> 
     </Grid> 
    </Grid> 
</UserControl> 

Comme vous pouvez le voir, je 7 langues que je veux traiter. En ce moment, cela charge la version anglaise de mon texte très bien. J'ai passé la plus grande partie de la journée à essayer de trouver comment changer la liaison dans mon code pour l'échanger quand j'en avais besoin (disons quand je change de langue via une liste déroulante).

Toute aide serait géniale!

Répondre

1

Vous vous y trompez. La meilleure pratique pour la localisation dans Silverlight consiste à utiliser des fichiers de ressources contenant les mots-clés traduits. Voici un peu plus d'informations à ce sujet:

http://msdn.microsoft.com/en-us/library/cc838238%28VS.95%29.aspx

EDIT:

Voici un exemple où j'utilise une classe d'aide pour tenir les chaînes traduites. Ces traductions peuvent ensuite être chargées à partir de n'importe où. Fichiers de ressources statiques, xml, base de données ou autre. Je l'ai fait rapidement, donc ce n'est pas très stable. Et il ne fait que basculer entre l'anglais et le suédois.

XAML:

<UserControl x:Class="SilverlightApplication13.MainPage" 
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
      xmlns:local="clr-namespace:SilverlightApplication13" 
      mc:Ignorable="d" 
      d:DesignWidth="640" 
      d:DesignHeight="480"> 

    <UserControl.Resources> 
     <local:TranslationHelper x:Key="TranslationHelper"></local:TranslationHelper> 
    </UserControl.Resources> 

    <Grid x:Name="LayoutRoot"> 
     <StackPanel> 

      <TextBlock Margin="10" 
         Text="{Binding Home, Source={StaticResource TranslationHelper}}"></TextBlock> 

      <TextBlock Margin="10" 
         Text="{Binding Contact, Source={StaticResource TranslationHelper}}"></TextBlock> 

      <TextBlock Margin="10" 
         Text="{Binding Links, Source={StaticResource TranslationHelper}}"></TextBlock> 

      <Button Content="English" 
        HorizontalAlignment="Left" 
        Click="BtnEnglish_Click" 
        Margin="10"></Button> 

      <Button Content="Swedish" 
        HorizontalAlignment="Left" 
        Click="BtnSwedish_Click" 
        Margin="10"></Button> 
     </StackPanel> 
    </Grid> 
</UserControl> 

code-behind + classe TranslationHelper:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Net; 
using System.Windows; 
using System.Windows.Controls; 
using System.Windows.Documents; 
using System.Windows.Input; 
using System.Windows.Media; 
using System.Windows.Media.Animation; 
using System.Windows.Shapes; 
using System.Windows.Threading; 
using System.ComponentModel; 

namespace SilverlightApplication13 
{ 
    public partial class MainPage : UserControl 
    { 
     public MainPage() 
     { 
      InitializeComponent(); 

      //Default 
      (this.Resources["TranslationHelper"] as TranslationHelper).SetLanguage("en-US"); 
     } 

     private void BtnEnglish_Click(object sender, RoutedEventArgs e) 
     { 
      (this.Resources["TranslationHelper"] as TranslationHelper).SetLanguage("en-US"); 
     } 

     private void BtnSwedish_Click(object sender, RoutedEventArgs e) 
     { 
      (this.Resources["TranslationHelper"] as TranslationHelper).SetLanguage("sv-SE"); 
     } 
    } 

    public class TranslationHelper : INotifyPropertyChanged 
    { 
     private string _Contact; 

     /// <summary> 
     /// Contact Property 
     /// </summary> 
     public string Contact 
     { 
      get { return _Contact; } 
      set 
      { 
       _Contact = value; 
       OnPropertyChanged("Contact"); 
      } 
     } 

     private string _Links; 

     /// <summary> 
     /// Links Property 
     /// </summary> 
     public string Links 
     { 
      get { return _Links; } 
      set 
      { 
       _Links = value; 
       OnPropertyChanged("Links"); 
      } 
     } 

     private string _Home; 

     /// <summary> 
     /// Home Property 
     /// </summary> 
     public string Home 
     { 
      get { return _Home; } 
      set 
      { 
       _Home = value; 
       OnPropertyChanged("Home"); 
      } 
     } 



     public TranslationHelper() 
     { 
      //Default 
      SetLanguage("en-US"); 
     } 

     public void SetLanguage(string cultureName) 
     { 
      //Hard coded values, need to be loaded from db or elsewhere 

      switch (cultureName) 
      { 
       case "sv-SE": 
        Contact = "Kontakt"; 
        Links = "Länkar"; 
        Home = "Hem"; 
        break; 

       case "en-US": 
        Contact = "Contact"; 
        Links = "Links"; 
        Home = "Home"; 
        break; 

       default: 
        break; 
      } 
     } 

     public event PropertyChangedEventHandler PropertyChanged; 

     protected virtual void OnPropertyChanged(string propertyName) 
     { 
      if (PropertyChanged != null) 
      { 
       PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); 
      } 
     } 
    } 
} 
+0

Est-ce que cela me permettra de définir la langue de façon dynamique sans devoir recharger l'application? Dans les exemples sur MSDN redirige l'utilisateur vers une nouvelle page –

+1

Aha. Maintenant, je vois ce que vous êtes après. Non, l'utilisateur ne pourra pas changer de langue à la volée lors de l'utilisation de ressources statiques. Si c'est ce dont vous avez besoin, vous devriez probablement aller avec la liaison de données. Mais votre exemple de code me semble toujours trop compliqué. Je prépare un exemple de code de mon cru. Je vais le poster ici bientôt. –

+0

Existe-t-il un moyen pour que cela fonctionne lorsque vous chargez un enfant, il peut partager les ressources? J'ai essayé de mettre ceci dans un dossier de classe mais il ne veut pas le charger quand mon UC est dans un sous-dossier –

2

On dirait que vous cherchez code comme ceci:

Title.SetBinding(TextProperty, new Binding { Path = new PropertyPath(language) }); 

Tout ce qu'il fait est de créer une nouvelle liaison pour la langue que vous avez demandé et l'utiliser pour remplacer l'ancienne liaison pour la propriété Text du titre.

+0

Je fini par utiliser ce aussi bien pour certaines parties. Dommage que je ne puisse pas marquer les deux réponses comme cochées. –

Questions connexes