項目介紹
以Notes項目為例,The Notes application consists of one solution containing four projects, as shown in the following screenshot:
The projects are:
- Notes – This project is the .NET Standard library project that holds all of the shared code and shared UI.【包含所有共享代碼和共享 UI 的 .NET Standard 庫項目】
- Notes.Android – This project holds Android-specific code and is the entry point for the Android application.
- Notes.iOS – This project holds iOS-specific code and is the entry point for the iOS application.
- Notes.UWP – This project holds Universal Windows Platform (UWP) specific code and is the entry point for the UWP application.
程序剖析
1、.NET Standard 庫項目
包含 NuGet 和 SDK :
- NuGet–已添加到項目的 Xamarin 和 sqlite-pcl NuGet 包。
- SDK –
NETStandard.Library
元包。
2、項目還包括多個文件:
- Data\NoteDatabase.cs –此類包含用於創建數據庫、從中讀取數據、向其中寫入數據和從中刪除數據的代碼。
- Models\Note.cs –此類定義一個
Note
模型, 其實例存儲有關應用程序中每個注釋的數據。 - App.xaml -
App
類的 XAML 標記,該類定義應用程序的資源字典。 - App.xaml.cs -
App
類的代碼隱藏,該類負責實例化應用程序在每個平台上將顯示的首頁,並處理應用程序生命周期事件。 - AssemblyInfo.cs –此文件包含項目的應用程序屬性, 該屬性應用於程序集級別。
- NotesPage -
NotesPage
類的 xaml 標記, 用於定義在應用程序啟動時顯示的頁的 UI。 - NotesPage.xaml.cs -
NotesPage
類的代碼隱藏, 該類包含用戶與頁面交互時執行的業務邏輯。 - NoteEntryPage -
NoteEntryPage
類的 xaml 標記, 它定義用戶輸入備注時顯示的頁面的 UI。 - NoteEntryPage.xaml.cs -
NoteEntryPage
類的代碼隱藏, 該類包含用戶與頁面交互時執行的業務邏輯。
體系結構和應用程序基礎知識
共享代碼通常位於 .NET Standard 庫中,平台特定應用程序將使用此共享代碼。
- App.xaml
若要最大限度重用啟動代碼,Xamarin.Forms 應用程序需有一個名為 App
的單個類,該類負責實例化應用程序在每個平台上將顯示的首頁【MainPage】:MainPage = new NavigationPage(new NotesPage());
- AssemblyInfo.cs
包含項目的應用程序屬性。XamlCompilation
特性用於控制在生成時還是運行時編譯 XAML , 以便將 xaml 直接編譯為中間語言。
啟動應用程序
- IOS
若要在 iOS 中啟動最初的Xamarin. Forms 頁面, Notes.ios 項目定義了從FormsApplicationDelegate
類繼承的AppDelegate
類。

namespace Notes.iOS { [Register("AppDelegate")] public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate { public override bool FinishedLaunching(UIApplication app, NSDictionary options) { global::Xamarin.Forms.Forms.Init(); LoadApplication(new App()); return base.FinishedLaunching(app, options); } } }
重寫FinishedLaunching
方法中,通過調用Init方法來初始化 Xamarin.Forms framework ,這導致了Xamarin的ios特定實現在 根視圖控制器(通過LoadApplication方法調用)之前加載。
- Android
若要在 Android 中啟動最初的 Xamarin. Forms 頁面, Notes.android 項目包含了一個帶MainLauncher
屬性的Activity
,此Activity從FormsAppCompatActivity
類繼承:

namespace Notes.Droid { [Activity(Label = "Notes", Icon = "@mipmap/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)] public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity { protected override void OnCreate(Bundle savedInstanceState) { TabLayoutResource = Resource.Layout.Tabbar; ToolbarResource = Resource.Layout.Toolbar; base.OnCreate(savedInstanceState); Xamarin.Essentials.Platform.Init(this, savedInstanceState); global::Xamarin.Forms.Forms.Init(this, savedInstanceState); LoadApplication(new App()); } } }
重寫OnCreate方法中,通過調用Init方法來初始化 Xamarin.Forms framework ,這導致了Xamarin的android特定實現在 根視圖控制器(通過LoadApplication方法調用)之前加載。
- 通用 Windows 平台(UWP)
從 App 類調用初始化 Xamarin.Forms 框架的 Init 方法(將特定於 UWP 的 Xamarin.Forms 實現加載到應用程序)
初始Xamarin.Forms頁由MainPage類啟動,再加載 Xamarin.Forms 應用程序(App.Xaml) 。
Universal Windows Platform apps can be built with Xamarin.Forms, but only using Visual Studio on Windows.
用戶界面
有四個主要的控件組:
- 頁面 - Xamarin.Forms 頁呈現跨平台移動應用程序屏幕。 Notes 應用程序使用
ContentPage
類(繼承它)顯示單個屏幕。 有關頁面的詳細信息,請參閱 Xamarin.Forms 頁面。 - 視圖 - Xamarin.Forms 視圖是顯示在用戶界面上的控件,如標簽、按鈕和文本輸入框,程序中對應
ListView
、Editor
和Button
。 有關視圖的詳細信息,請參閱 Xamarin.Forms 視圖。 - 布局 - Xamarin.Forms 布局是用於將視圖組合到邏輯結構的容器。 Notes 應用程序使用
StackLayout
類在垂直堆棧中排列視圖和Grid
類來水平排列按鈕。 有關布局的詳細信息,請參閱 Xamarin.Forms 布局。 - 單元格 - Xamarin.Forms 單元格是用於列表中項的專門元素,描述列表中每個項的繪制方式。 Notes 應用程序使用
TextCell
為列表中的每一行顯示兩個項。 有關單元格的詳細信息,請參閱 Xamarin.Forms 單元格。
在運行時,每個控件都會映射到其本身的本機等效項(即呈現的內容)。
- 布局
Notes 應用程序使用StackLayout
來簡化跨平台應用程序開發, 而不考慮屏幕大小。 根據添加順序,以垂直方式或水平方式逐個放置每個子元素。 StackLayout
使用的空間大小取決於 HorizontalOptions
和 VerticalOptions
屬性的設置方式,但默認情況下,StackLayout
嘗試使用整個屏幕。
默認情況下StackLayout
,為垂直方向。 但是, 可以通過改StackLayout.Orientation
屬性為水平方向。
可以通過HeightRequest
和WidthRequest
屬性設置視圖的大小。
- 響應用戶交互
XAML 中定義的對象可觸發在cs文件中處理的事件。
導航Navigation
Xamarin.Forms 提供多種不同的頁導航體驗,具體取決於使用的 Page
類型。對於ContentPage
實例, 導航可以是分層的, 也可以是模式。 有關模式導航的信息, 請參閱Xamarin. Forms 模式頁面。
注:CarouselPage、
MasterDetailPage
和 TabbedPage
類提供替代導航體驗。 有關詳細信息,請參閱導航。
NavigationPage
在層次結構導航【分層導航】中 NavigationPage
類用於根據需要,在ContentPage
對象堆棧中向前和向后導航。 此類將導航實現為 Page
對象的后進先出 (LIFO) 堆棧。 若要從一頁移動到另一頁,應用程序會將新頁推送到導航堆棧中,在堆棧中,該頁會變為活動頁。 若要返回到前一頁,應用程序會從導航堆棧彈出當前頁,而使最頂層的頁成為活動頁。
NavigationPage
類還會將一個導航欄添加到頁面頂部,此導航欄包括 標題和平台相應的“返回”按鈕,通過此按鈕可返回上一頁。
頁面跳轉
所有 ContentPage
實例都具有 Navigation
屬性,可提供修改頁面堆棧的方法,
eg,從頁面跳到其他頁面,await Navigation.PushAsync(new NoteEntryPage()); //這將導致NoteEntryPage新
對象被推送到導航堆棧上, 並將其變成活動頁。
通過設備上的返回按鈕(無論是設備上的物理按鈕還是屏幕按鈕),可以從導航堆棧中彈出活動頁。 若要以編程方式返回原始頁,NoteEntryPage
對象必須調用 PopAsync
方法:await Navigation.PopAsync();
數據綁定
數據綁定在用戶界面和應用程序之間建立連接。
參考:Xamarin.From中的Data binding(數據綁定)(一)
數據綁定連接兩個對象,即源和目標。 源對象提供數據, 目標對象使用(並經常顯示)來自源對象的數據。 例如, Editor
(目標對象) 通常會將Text
屬性綁定到源對象中string
的屬性。 下圖說明了這種綁定關系:
數據綁定的主要優點是讓你無需再擔心視圖和數據源之間的數據同步。 底層的綁定框架源會將源對象中的更改自動推送到目標對象,且目標對象中的更改可選擇性地推送回源對象。
建立數據綁定的過程分為兩個步驟:
- 目標對象的
BindingContext
屬性必須設置為源。 - 必須在目標和源之間建立綁定。
實現綁定有兩種方式:在xaml或者cs中
每種又分使用BindingContext與否。
1、在 XAML 中【常用方式】
不使用BingingContext:可通過使用 Binding
標記擴展實現。
在 Notes 應用程序中, 綁定目標Editor用於
顯示note, 而NoteEntryPage設置的
綁定源。BindingContext即N
ote對象
是
await Navigation.PushAsync(new NoteEntryPage { BindingContext = new Note() });
NoteEntryPage頁面中Editor然后綁定Note對象的Text屬性:
<Editor Placeholder="Enter your note" Text="{Binding Text}" ... />
在 Editor.Text
屬性(目標)和源對象(Note實例)的 Text
屬性之間建立綁定。 在Editor中所做
的更改會自動傳播到Note
對象。 同樣, 如果對Note.Text
屬性進行了更改, Xamarin 綁定引擎也將更新Editor的內容,這稱為雙向綁定。
使用BingingContext:
BindingContext="{x:Reference Name=slider}"
Rotation="{Binding Path=Value}"/>
小結:將Binding的Source屬性或者BindingContext屬性設置為x:Reference標記擴展,以引用頁面上的另一個視圖(源對象)。 這兩個屬性的類型為Object,可以將它們設置為任何包含適合於綁定源的屬性的對象。
如果兩者都已設置,則 Binding
的 Source
屬性優先於 BindingContext
。
2、只在cs中設定
需要設置以下
BindingContext
屬性指定源對象。SetBinding
方法指定目標屬性和源屬性。
public BasicCodeBindingPage() { InitializeComponent(); label.BindingContext = slider; label.SetBinding(Label.RotationProperty, "Value"); }
注:若 目標和源 都是控件,則可以完全在xaml中實現綁定:

<StackLayout Padding="10, 0"> <Label x:Name="label" Text="TEXT" FontSize="80" HorizontalOptions="Center" VerticalOptions="CenterAndExpand" BindingContext="{x:Reference Name=slider}" Rotation="{Binding Path=Value}" /> <Slider x:Name="slider" Maximum="360" VerticalOptions="CenterAndExpand" /> </StackLayout>
可以簡化“基本 XAML 綁定” 頁上顯示的標記:XAML 標記擴展名(如 x:Reference
和 Binding
)可以定義“內容屬性” 屬性,對於 XAML 標記擴展,這意味着不需要出現屬性名稱。 Name
屬性是 x:Reference
的內容屬性,Path
屬性是 Binding
的內容屬性,這意味着可以從表達式中刪除它們:

<Label Text="TEXT" FontSize="80" HorizontalOptions="Center" VerticalOptions="CenterAndExpand" BindingContext="{x:Reference slider}" Rotation="{Binding Value}" />
更多參考:基本綁定
樣式Styling
Xamarin.forms應用程序通常包含多個具有相同外觀的視覺元素。 設置每個視覺對象的外觀可能是重復性的並且容易出錯。 相反, 可以創建用於定義外觀的樣式, 然后將其應用於所需的視覺對象。
Style
類將一些屬性值分組到一個對象中, 然后可以將該對象應用於多個視覺元素實例。 樣式存儲在ResourceDictionary,可以針對
應用程序級別、頁面級別或視圖級別。 使用范圍如下:
Style
instances defined at the application level can be applied throughout the application. 【應用程序級別定義的style 可以在整個應用程序中使用】Style
instances defined at the page level can be applied to the page and to its children.【頁面級別定義的style 可以在此頁面或者其子頁面中使用,eg: <Style TargetType="{x:Type ContentPage}"】Style
instances defined at the view level can be applied to the view and to its children.【視圖級別定義的style 可以在此視圖或者子視圖使用,eg:<Style TargetType="{x:Type Editor}">】
注:在整個應用程序中使用的所有樣式均存儲在應用程序的ResourceDictionary中, 以避免重復。 但是,XAML中的應用程序的ResourceDictionary中不應包含 用於特定於頁面的Style, 因為在應用程序啟動時將分析資源,而不是在頁需要時進行分析。
每個Style
實例都包含一個或多個Setter
對象的集合。Setter
每個對象都有一個Property
和一個Value
。 屬性是應用樣式的元素的可綁定屬性的名稱,值是應用於屬性的值。
eg:NoteEntryPage頁面中的定義的Style
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="Notes.NoteEntryPage" Title="Note Entry"> <ContentPage.Resources> <!-- Implicit styles --> <Style TargetType="{x:Type Editor}"> <Setter Property="BackgroundColor" Value="{StaticResource AppBackgroundColor}" /> </Style> ... </ContentPage.Resources> ... </ContentPage>
TargetType為Editor,表示NoteEntryPage頁面中所有的Editor都適用於此樣式。
注:除了可以使用XAMl樣式,也還支持CSS樣式。 請參閱設置使用級聯樣式表 (CSS) 的 Xamarin 應用程序樣式。
提供特定於平台的樣式
OnPlatform
標記擴展允許你根據每個平台自定義 UI 外觀:

<Application xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="Notes.App"> <Application.Resources> ... <Color x:Key="iOSNavigationBarColor">WhiteSmoke</Color> <Color x:Key="AndroidNavigationBarColor">#2196F3</Color> <Color x:Key="iOSNavigationBarTextColor">Black</Color> <Color x:Key="AndroidNavigationBarTextColor">White</Color> <Style TargetType="{x:Type NavigationPage}"> <Setter Property="BarBackgroundColor" Value="{OnPlatform iOS={StaticResource iOSNavigationBarColor}, Android={StaticResource AndroidNavigationBarColor}}" /> <Setter Property="BarTextColor" Value="{OnPlatform iOS={StaticResource iOSNavigationBarTextColor}, Android={StaticResource AndroidNavigationBarTextColor}}" /> </Style> ... </Application.Resources> </Application>