这节主要演示了如何通过添加第二个屏幕来跟踪应用程序的call历史来扩展Phoneword应用程序。最终如下:
按如下步骤扩展Phoneword
在Phoneword项目右键新建Content Page,命名为CallHistoryPage
修改后CallHistoryPage.xaml如下:
xml version="1.0" encoding="UTF-8"?> <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:local="clr-namespace:Phoneword;assembly=Phoneword" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="Phoneword.CallHistoryPage" Title="Call History"> <ContentPage.Padding> <OnPlatform x:TypeArguments="Thickness"> <On Platform="iOS" Value="20, 40, 20, 20" /> <On Platform="Android, UWP" Value="20" /> OnPlatform> ContentPage.Padding> <StackLayout> <ListView ItemsSource="{x:Static local:App.PhoneNumbers}" /> StackLayout> ContentPage>
双击Phoneword项目的App.xaml.cs文件
添加PhoneNumbers属性的声明,在App构造函数中初始化该属性,并将MainPage属性初始化为NavigationPage。PhoneNumbers被用于存储应用程序打的每个电话号码
using System.Collections.Generic; using Xamarin.Forms; using Xamarin.Forms.Xaml; [assembly: XamlCompilation(XamlCompilationOptions.Compile)] namespace Phoneword { public partial class App : Application { public static IList<string> PhoneNumbers { get; set; } public App() { InitializeComponent(); PhoneNumbers = new List<string>(); MainPage = new NavigationPage(new MainPage()); } ... } }
双击Phoneword项目的MainPage.xaml文件
在StackLayout控件的末尾添加一个按钮控件,该按钮被用于导航到拨打历史页面
<StackLayout VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand" Orientation="Vertical" Spacing="15"> ... <Button x:Name="callButton" Text="Call" IsEnabled="false" Clicked="OnCall" /> <Button x:Name="callHistoryButton" Text="Call History" IsEnabled="false" Clicked="OnCallHistory" /> StackLayout>
打开隐藏文件MainPage.xaml.cs,添加OnCallHistory事件处理程序方法,并修改OnCall事件处理程序方法,将转换后的电话号码添加到App.PhoneNumbers集合中,并且如果dialer变量不为null时使能callHistoryButton
using System; using Xamarin.Forms; namespace Phoneword { public partial class MainPage : ContentPage { ... async void OnCall(object sender, EventArgs e) { ... if (dialer != null) { App.PhoneNumbers.Add (translatedNumber); callHistoryButton.IsEnabled = true; dialer.Dial (translatedNumber); } ... } async void OnCallHistory(object sender, EventArgs e) { await Navigation.PushAsync (new CallHistoryPage ()); } } }
下节剖析该扩展