- dDownload SimpleCurrencyConverter – 120.76 KB
Introduction
We will build a simple currency converter using a converter web service from start to finish for the Windows
Phone 7 using Microsoft Visual Studio Express 2010 for the Windows Phone.
Background
Before we begin you need to download and setup the Windows Phone Developer Tools . Michael Crump has a great step by step tutorial on setting up everything you need to develop for Windows Phone 7. you can find it here.
You might also want to go through the tutorial in the link to build a basic Phone 7 app to get you upto speed.
Using the code
From Visual C# , select Windows Phone Aplication and name it SimpleCurrencyConverter and click ok.
You should see the the following environment. if you cannot see the properties window , press Ctrl+W+P. you can also go to View > Other Windows > Properties Window to view the properties window.
ComboBox ScrollViewer.VerticalScrollBarVisibility=”Auto” ItemsSource=”{Binding ElementName=ConverterPage, Path=Locations}” Margin=”179,139,70,450″ Name=”cmbCurrFrom”> ComboBox.ItemTemplate> DataTemplate> TextBlock FontSize=”30″ Foreground=”Black” Text=”{Binding Path=Location}”>/TextBlock> /DataTemplate>/ComboBox.ItemTemplate>/ComboBox>ComboBox ItemsSource=”{Binding ElementName=ConverterPage, Path=Locations}” Margin=”179,223,70,370″ Name=”cmbCurrTo” ScrollViewer.VerticalScrollBarVisibility=”Auto”>ComboBox.ItemTemplate>DataTemplate> TextBlock FontSize=”30″ Foreground=”Black” Text=”{Binding Path=Location}” />/DataTemplate>/ComboBox.ItemTemplate>/ComboBox>
Add a button and name is btnConvert and change its content to “Convert”.
Rename the textblocks and arrange them as you wish to make it look pretty. As you can see I haven’t done that great of a job prettying it up
Hope you do a better job. It should look something like this …
We also need to limit the users from entering alphabets into the converter from text box. First set the Text to an empty string (Text=””) for your two textboxes. Microsoft provides us with a few different keyboard layouts depending on the context that we are using the text box. This can be set using the Input Scope of your textbox. You can read more about input scope here , here and here .
We still have one problem .even with the input scope set , the users can still enter special characters into the textbox. We will add add this check on the textchanged event, only letting the users enter numbers.
I found this quick and dirty code that checks for numbers here . Add this method to your MainPage.xaml.cs ..
public void txtConvertedFrom_TextChanged(object sender, TextChangedEventArgs e) { bool bNeedToUpdate = false; StringBuilder szNumbersOnly = new StringBuilder(); TextBox textSource = sender as TextBox; if (null == textSource) return; foreach (char ch in textSource.Text) { if ((“0123456789″).Contains(ch.ToString())) { szNumbersOnly.Append(ch); } else { bNeedToUpdate = true; } } if (bNeedToUpdate) { textSource.Text = szNumbersOnly.ToString(); textSource.SelectionStart = szNumbersOnly.Length; } }
Hook this up to the textchanged event of your textbox ..
TextBox Height=”72″ HorizontalAlignment=”Left” Margin=”179,26,0,0″ Name=”txtConvertedFrom” Text=”” VerticalAlignment=”Top” Width=”200″ TextChanged=”txtConvertedFrom_TextChanged” >
Now we will populate the dropdownlists with the country names. we will use a free webservice to populate the dropwonlists and also to get the conversion rates.
First, we need to add the service reference to our project. In your solution explorer , right click on References and click on Add Service Reference.
IN the window that pops up , enter the web service url webservicex.net/CurrencyConvertor.asmx?WSDL in the address box. Enter ConverterService in the NameSpace textbox. Click GO. YOu should see a list of services . Click OK.
Now we need to populate our dropdownlists with the countries/currencies list from the Currency Converter Web Service. we will do this using as Observable Collection . YOu can read about Observable Collections here .
Add this reference to your page:
using System.Collections.ObjectModel;
We need to add a “LocationUnit” class to setup the Observable Collection .
Add this code within your namespace ..
public class LocationUnit { public string Location { get; set; } public string URL { get; set; } }
Add the following code at the beginning of your class , before your constructor.
public static readonly DependencyProperty _locations = DependencyProperty.Register(“Locations”, typeof(ObservableCollection), typeof(PhoneApplicationPage), new PropertyMetadata(null)); public ObservableCollection Locations { get { return (ObservableCollection)GetValue(_locations); } set { SetValue(_locations, value); } }
Initialize the ObservableCollection in your constructor.
InitializeComponent();Locations = new ObservableCollection();>
Now we’ll populate the dropwonlists with the countries/currencies list from the Currency Converter Webservice.
There is onw little problem with this webservice.It returns the currencies list as an enum , which we can’t bind to the drop down. we need to convert it into a string array. we will use a helper class to convert the enum into a string array.you can find a pretty good example here.
Add this within your CurrencyConverter namespace:
public static class EnumHelper { public static string[] GetNames(Type enumType) { FieldInfo[] fieldInfo = enumType.GetFields(BindingFlags.Static | BindingFlags.Public); return fieldInfo.Select(f => f.Name).ToArray(); } public static string[] GetNames(Enum e) { List enumNames = new List(); foreach (FieldInfo fi in e.GetType().GetFields(BindingFlags.Static | BindingFlags.Public)) { enumNames.Add(fi.Name); } return enumNames.ToArray(); } }
Now we’ll add the method that populates the dropwonlists:
public void GetData(){ foreach (string s in EnumHelper.GetNames(typeof(ConverterService.Currency))) { LocationUnit unit = new LocationUnit() { Location = s, URL = s }; Locations.Add(unit); }}
Call this method in your constructor
// Constructor public MainPage() { InitializeComponent(); Locations = new ObservableCollection(); GetData(); }
We need to bind the two dropdownlists to our collection.Add this to your dropdowns in your xaml files..
“Auto”>ItemsSource=”{Binding ElementName=ConverterPage, Path=Locations}” Margin=”179,139,70,450″ Name=”cmbCurrFrom”>
Add the Name property at the top of your xaml:
“CurrencyConverter.MainPage” x:name=”ConverterPage”>
Now run your application and you should see your dropdownlists populated with the currency names.
Now we need to write code to call the webservice when the user clicks the convert button to get the conversion rate between the two selected currencies.
Add these two methods to your MainPage.xaml.cs file.
private void btnConvert_Click(object sender, RoutedEventArgs e) { ConverterService.CurrencyConvertorSoapClient aobClient = new ConverterService.CurrencyConvertorSoapClient(); aobClient.ConversionRateCompleted += new EventHandler(aobClient_ConversionRateCompleted); LocationUnit selectedLocationFrom = (from c in Locations where c.Location == ((LocationUnit)cmbCurrFrom.SelectedItem).Location select c).First(); LocationUnit selectedLocationTo = (from c in Locations where c.Location == ((LocationUnit)cmbCurrTo.SelectedItem).Location select c).First(); ConverterService.Currency currFrom = (ConverterService.Currency)Enum.Parse(typeof(ConverterService.Currency), selectedLocationFrom.Location, true); ConverterService.Currency currTo = (ConverterService.Currency)Enum.Parse(typeof(ConverterService.Currency), selectedLocationTo.Location, true); aobClient.ConversionRateAsync(currFrom, currTo); } void aobClient_ConversionRateCompleted(object sender, ConverterService.ConversionRateCompletedEventArgs e) { double adblResult = Convert.ToDouble(txtConvertedFrom.Text) * e.Result; txtConvertedTo.Text = adblResult.ToString(); }.conversionratecompletedeventargs>
The first method handles the button click event . we create an Client object for the webservice and call the ConversionRate method to get the conversion rate between the two selected currencies.since the request is asynchronous we need a method to handle the event when the webservice sends us the conversion rate. The aobClient_ConversionRateCompleted handles this event . we multiply the conversion rate with the amount entered and set the value of gthe converted to textbox with this amount.
Open MainPage.xaml and hook up the buttonclick event to the method we just wrote…
button content=”Convert” height=”72″ horizontalalignment=”Left” margin=”29,298,0,0″ name=”btnConvert” verticalalignment=”Top” width=”160″ click=”function click() { [native code] }”>/button>
Run your application , enter an amount , select two currencies and click convert.
- Microsoft's Windows 7 mobile system | Windows Phone 7 is different … Microsoft’s Window 7 is a new business mobile operating system.a…
- Non Functional Currency Definition | Currency Converter Calculator … STOCK MARKET DEVELOPMENT AND ECONOMIC GROWTH: EVIDENCE OF underdeveloped nation…
- HOSA 1/4¿¿ PHONE (F) – 1/4¿¿ PHONE (M) COILED, 25 ft. HEADPHONE … HOSA 1/4¿¿ PHONE (F) – 1/4¿¿ PHONE (M) COILED, 25…
- Importance of Pdf Converter | Software Tools Importance of PDF Converter It is very essential for the…
- DDVideo DVD to FLV Converter Gain 4.0 serial activation kegen … DDVideo DVD to FLV Converter Gain.a powerful DVD to FLV…
Related posts brought to you by Yet Another Related Posts Plugin.
Currency Converter For Windows Phone 7 — villagegatenews.com