×
Namespaces

Variants
Actions

Google Translate in Windows Phone

From Nokia Developer Wiki
Jump to: navigation, search

This article demonstrates how to implement Google Translate as a free service in Windows Phone.

WP Metro Icon Web.png
SignpostIcon XAML 40.png
WP Metro Icon WP8.png
SignpostIcon WP7 70px.png
Article Metadata
Code ExampleTested with
Devices(s): Nokia Lumia 800, 820,920
CompatibilityPlatform Security
Signing Required: Self-Signed
Capabilities: ID_CAP_NETWORKING
Article
Created: somnathbanik (19 Apr 2013)
Last edited: hamishwillee (25 Nov 2013)

Contents

Introduction

Google provides a paid translation service: Google Translate API. This article uses the free Google Translate web service to get the response in HTML format and parse the actual translated text using RegularExpressions.

Note.pngNote: There are other translation services including Microsoft Translate API (free). These have not been tried, and may offer different or better translation results than Google.

Implementation

Create a standard Windows Phone Project

Let’s create a standard Windows Phone Application Project

  • Launch Visual Studio
  • Click on File
  • Click on New Project
  • Select Windows Phone Application (Visual C# Template)
  • Add Name and Location of the project
  • Click OK to create the project.

Adding UI controls on application page

  • We create two ListPicker which is a part of Windows Phone Toolkit to select To and From of the language. Two TextBox to write and display our text. And a submit Button to process the web request.
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"  DataContext="{StaticResource Languages}">
<StackPanel Orientation="Vertical">
<StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock x:Name="TextBlockLanguageFrom" FontFamily="Segoe WP" FontSize="40" Margin="{StaticResource PhoneMargin}" Foreground="{StaticResource PhoneAccentBrush}" Text="From : " />
<toolkit:ListPicker HorizontalAlignment="Left"
x:Name="ListPickerLanguageFrom"
Header=""
ItemsSource="{Binding language}"
SelectedIndex="5"
ExpansionMode="FullScreenOnly"
FullModeItemTemplate="{StaticResource LanguagesTemplate}"
SelectionChanged="ListPickerLanguageFrom_SelectionChanged" Width="290" />
</StackPanel>
<TextBox Name="TextBoxTranslateFrom" TextWrapping="Wrap" Width="460" Height="150" HorizontalAlignment="Left" VerticalAlignment="Top"/>
</StackPanel>
<StackPanel Margin="0,30,0,20">
<StackPanel Orientation="Horizontal" >
<TextBlock x:Name="TextBlockLanguageTo" FontFamily="Segoe WP" FontSize="40" Margin="{StaticResource PhoneMargin}" Foreground="{StaticResource PhoneAccentBrush}" Text="To : " />
<toolkit:ListPicker HorizontalAlignment="Left" Margin="63,0,0,0" VerticalAlignment="Center"
x:Name="ListPickerLanguageTo"
Header=""
ItemsSource="{Binding language}"
SelectedIndex="7"
ExpansionMode="FullScreenOnly"
FullModeItemTemplate="{StaticResource LanguagesTemplate}"
SelectionChanged="ListPickerLanguageTo_SelectionChanged" Width="290" />
</StackPanel>
<TextBox Name="TextBoxTranslateTo" TextWrapping="Wrap" Width="460" Height="150" HorizontalAlignment="Left" VerticalAlignment="Top"/>
</StackPanel>
<Button Content="Submit" Height="72" Click="Button_Click" ></Button>
</StackPanel>
</Grid>
  • We also create a resource template for the ListPicker in the MainPage.xaml file
<phone:PhoneApplicationPage.Resources>
<library:Languages x:Key="Languages"/>
<DataTemplate x:Key="LanguagesTemplate">
<StackPanel Orientation="Horizontal">
<Rectangle
Fill="{StaticResource PhoneAccentBrush}"
Width="30"
Height="30"
Margin="0 0 12 0"/>
<TextBlock Text="{Binding}" FontFamily="Segoe WP" FontSize="51"/>
</StackPanel>
</DataTemplate>
</phone:PhoneApplicationPage.Resources>

Code behind

  • Add the following class to display the list of language in the ListPicker
    public class Languages : INotifyPropertyChanged
{
public IEnumerable<string> language { get; private set; }
public Languages()
{
language = "Arabic, Bulgarian, Chinese, Danish, Dutch, English, Filipino, Finnish, French, German, Greek, Hebrew, Hindi, Hungarian, Icelandic, Indonesian, Irish, Italian, Japanese, Korean, Latvian, Lithuanian, Macedonian, Malay, Maltese, Norwegian, Persian, Polish, Portuguese, Romanian, Russian, Serbian, Slovak, Slovenian, Spanish, Swedish, Thai, Turkish, Ukrainian, Vietnamese".Split(new Char[] { ',' });
}
private void InvokePropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if (null != handler)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
  • Add the following code to select To and From of the language
  //selected language from 
private void ListPickerLanguageFrom_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
AppModel.LanguageSelectedIndexFrom = 0;
AppModel.LanguageSelectedIndexFrom= ((ListPicker)sender).SelectedIndex;
AppModel.LanguageCodeFrom = SelectedLanguage.GetSelectedLanguageCode(AppModel.LanguageSelectedIndexFrom);
}
 
//selected language to
private void ListPickerLanguageTo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
AppModel.LanguageSelectedIndexTo = 0;
AppModel.LanguageSelectedIndexTo = ((ListPicker)sender).SelectedIndex;
AppModel.LanguageCodeTo = SelectedLanguage.GetSelectedLanguageCode(AppModel.LanguageSelectedIndexTo);
}
  • Add the following code to translate the text using a web service request and parse the HTML response using regular expression.
  //translate language
private void Button_Click(object sender, RoutedEventArgs e)
{
if (TextBoxTranslateFrom.Text != "")
{
string url = "http://translate.google.com/translate_t?text=" + TextBoxTranslateFrom.Text + "&sl=" + AppModel.LanguageCodeFrom + "&tl=" +AppModel.LanguageCodeTo;
WebClient webclient = new WebClient();
webclient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webclient_DownloadStringCompleted);
webclient.DownloadStringAsync(new Uri(url, UriKind.RelativeOrAbsolute));
}
else
{
MessageBox.Show("Enter text!");
}
}
void webclient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null)
{
try
{
Match CompareText = Regex.Match(e.Result, "(?<=<span id=result_box class=\"short_text\">)(.*?)(?=</span>)");
string[] TranslatedText = Regex.Split(CompareText.Value, "\">");
// MessageBox.Show(TranslatedText.GetValue(1).ToString());
TextBoxTranslateTo.Text = TranslatedText.GetValue(1).ToString();
}
catch (Exception ex) { }
}
}

Summary

There is nothing big in this example other than simple tips to get the text translated. Most of the code are called from a PhoneClassLibrary which is a part of the project reference. Please download the source code for better understanding of the code flow.

Related Article

Using Google Translate on Windows Phone - Nice implementation using Yahoo Query Language

Source Code

This page was last modified on 25 November 2013, at 08:55.
466 page views in the last 30 days.