Windows Phone 7货币转换器






4.81/5 (9投票s)
一个简单的货币转换应用程序,用于Windows Phone 7,使用Web服务
引言
我们将使用货币转换 Web 服务,从头到尾为 Windows Phone 7 构建一个简单的货币转换器,使用 Microsoft Visual Studio Express 2010 for Windows Phone。
背景
在开始之前,您需要下载并设置 Windows Phone 开发工具。Michael Crump 有一个很棒的循序渐进的教程,介绍了设置开发 Windows Phone 7 所需的一切。您可以在这里找到它。
您可能还想通过链接中的教程来构建一个基本的 Phone 7 应用,以便您能快速上手。
Using the Code
现在您已经设置好了一切,让我们开始构建货币转换器应用程序。
打开 Visual Studio 2010 for Phone 7,然后从“文件”菜单中选择“新建项目”。您应该会看到这个窗口...
从“Visual C#”中选择“Windows Phone 应用程序”,并将其命名为 SimpleCurrencyConverter
,然后单击“确定”。
您应该会看到以下环境。如果看不到属性窗口,请按 Ctrl+W+P。您也可以转到“视图”>“其他窗口”>“属性窗口”来查看属性窗口。
单击页面名称,然后在属性窗口中将“文本”设置为“货币转换器”,将“字体大小”设置为“48”。
我们的货币转换器需要四个 TextBlock、两个 TextBox、两个下拉列表和一个按钮。
您可以直接从工具箱拖放四个 TextBlock,或者拖放一个 TextBlock,然后复制粘贴其他三个。
从工具箱拖放两个 TextBox,将第一个命名为 txConvertedFrom
,将第二个命名为 txtConvertedTo
。将 width
设置为 40
。请注意,Visual Studio 会提供一些指南,帮助您对齐控件。您可以随意操作,根据需要调整大小和对齐。
现在,这里有点棘手,我们熟悉的下拉列表控件,如果您在 ASP.NET 上工作过一段时间,可能已经用过无数次了,但在工具箱里却找不到。这显然是因为它与“Metro UI”不兼容。但是,仍然可以通过代码添加它。请注意,Microsoft 的指南不推荐使用 dropdownlist 控件。但是,由于我们需要一个控件来绑定我们的 Web 服务数据,所以我们暂时使用它。
将以下内容添加到您的 Mainpage.xaml 中。
<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>
添加一个按钮,命名为 btnConvert
,并将其内容更改为“Convert
”。
重命名 textblock
并随意排列它们,使其看起来更美观。正如您所看到的,我在这方面做得不是很好。;)
希望您做得更好。它应该看起来像这样...

我们还需要限制用户在文本框中输入字母。首先,将两个文本框的“文本”设置为一个空字符串 (Text=""
)。Microsoft 为我们提供了几种不同的键盘布局,具体取决于我们使用文本框的上下文。这可以使用文本框的“输入范围”来设置。您可以在这里、这里和这里阅读有关输入范围的更多信息。
我们仍然有一个问题。即使设置了输入范围,用户仍然可以在文本框中输入特殊字符。我们将在 textchanged
事件中添加此检查,只允许用户输入数字。
我在这里找到了这段快速而简单的代码,用于检查数字。将此方法添加到您的 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;
}
}
将此方法挂接到您 textbox
的 textchanged
事件。
<TextBox Height="72" HorizontalAlignment="Left" Margin="179,26,0,0"
Name="txtConvertedFrom" Text="" VerticalAlignment="Top" Width="200"
TextChanged="txtConvertedFrom_TextChanged" >
现在,我们将用国家名称填充 dropdownlist
。我们将使用一个免费的 Web 服务来填充 dropdownlist
并获取汇率。
首先,我们需要为我们的项目添加服务引用。在您的解决方案资源管理器中,右键单击“引用”,然后单击“添加服务引用”。
在弹出的窗口中,在地址框中输入 Web 服务 URL http://www.webservicex.net/CurrencyConvertor.asmx?WSDL。在“命名空间” textbox
中输入 ConverterService
。单击“转到”。您应该会看到服务列表。单击“确定”。
现在我们需要使用 Observable Collection 将国家/货币列表从货币转换 Web 服务填充到我们的 dropdownlist
中。您可以在这里阅读有关 Observable Collection 的信息。
将此引用添加到您的页面
using System.Collections.ObjectModel;
我们需要添加一个“LocationUnit
”类来设置 Observable Collection。
将此代码添加到您的命名空间中:
public class LocationUnit
{
public string Location { get; set; }
public string URL { get; set; }
}
将以下代码添加到您的类开头,在构造函数之前。
public static readonly DependencyProperty _locations =
DependencyProperty.Register("Locations",
typeof(ObservableCollection<locationunit>), typeof(PhoneApplicationPage),
new PropertyMetadata(null));
public ObservableCollection<locationunit> Locations
{
get { return (ObservableCollection<locationunit>)GetValue(_locations); }
set { SetValue(_locations, value); }
}
在构造函数中初始化 ObservableCollection
。
InitializeComponent();
Locations = new ObservableCollection<locationunit>();
现在,我们将使用货币转换 Web 服务中的国家/货币列表来填充 dropdownlist
。
这个 webservice
有一个小问题。它返回的货币列表是一个 enum
,我们无法将其绑定到下拉列表。我们需要将其转换为 string
数组。我们将使用一个帮助类来将 enum
转换为 string
数组。您可以在这里找到一个相当不错的示例。
将此添加到您的 CurrencyConverter
命名空间中
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<string> enumNames = new List<string>();
foreach (FieldInfo fi in e.GetType().GetFields(
BindingFlags.Static | BindingFlags.Public))
{
enumNames.Add(fi.Name);
}
return enumNames.ToArray<string>();
}
}
现在我们将添加填充 dropdownlist
的方法
public void GetData()
{
foreach (string s in EnumHelper.GetNames(typeof(ConverterService.Currency)))
{
LocationUnit unit = new LocationUnit()
{
Location = s,
URL = s
};
Locations.Add(unit);
}
}
在构造函数中调用此方法
// Constructor
public MainPage()
{
InitializeComponent();
Locations = new ObservableCollection<locationunit>();
GetData();
}
我们需要将两个 dropdownlist
绑定到我们的 collection
。将此添加到您的 XAML 文件中的 dropdown
中。
<combobox scrollviewer.verticalscrollbarvisibility="Auto">
ItemsSource="{Binding ElementName=ConverterPage, Path=Locations}"
Margin="179,139,70,450" Name="cmbCurrFrom">
在 XAML 的顶部添加 Name
属性
<phoneapplicationpage x:class="CurrencyConverter.MainPage" x:name="ConverterPage">
现在运行您的应用程序,您应该会看到您的 dropdownlist
已填充货币名称。现在我们需要编写代码来在用户单击转换按钮时调用 webservice
,以获取两个选定货币之间的汇率。将这两个方法添加到您的 MainPage.xaml.cs 文件中。
private void btnConvert_Click(object sender, RoutedEventArgs e)
{
ConverterService.CurrencyConvertorSoapClient aobClient =
new ConverterService.CurrencyConvertorSoapClient();
aobClient.ConversionRateCompleted +=
new EventHandler<converterservice.conversionratecompletedeventargs>(
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();
}
第一个方法处理按钮单击事件。我们为 webservice
创建一个 Client
对象,并调用 ConversionRate
方法来获取两个选定货币之间的汇率。由于请求是异步的,我们需要一个方法来处理 Web 服务发送转换率时的事件。aobClient_ConversionRateCompleted
处理此事件。我们将汇率乘以输入的金额,并将 g 转换后的值设置为该金额的 textbox
。打开 MainPage.xaml 并将 buttonclick
事件挂接到我们刚刚编写的方法。
<button content="Convert" height="72" horizontalalignment="Left" margin="29,298,0,0"
name="btnConvert" verticalalignment="Top" width="160"
click="function click() { [native code] }">
</button>
运行您的应用程序,输入金额,选择两种货币,然后单击“转换”。

历史
- 2010 年 11 月 15 日:初始发布