c#開發移動APP-Xamarin入門擴充套件
阿新 • • 發佈:2018-11-08
這節主要演示瞭如何通過新增第二個螢幕來跟蹤應用程式的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>
雙擊
新增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 ()); } } }
下節剖析該擴充套件