Xamarin.Forms 是一个跨平台的、基于原生控件的UI工具包,开发人员可以轻松创建适用于 Android、iOS 以及 Windows Phone 的用户界面。通过使用平台的原生控件渲染界面,应用在外观上与平台完全一致。本文介绍如何使用 Xamarin.Forms 进行应用程序开发。
简介
Xamarin.Forms 帮助开发人员快速构建跨平台UI,通过一次编码生成多平台界面,减少重复工作。它允许使用 C# 语言开发,应用程序完全是原生的,不受浏览器沙盒或底层API限制,可以调用操作系统提供的API,如 iOS 的 CoreMotion 或安卓的 Google Play Services。架构上采用共享逻辑层的跨平台方案,通常使用 Portable Libraries 或 Shared Projects 共享代码。
系统需求
开发 Xamarin.Forms 应用需满足以下系统需求:
- iOS:需要一台 Mac 作为构建主机,运行 OS X Lion 或更新版本,安装 Xcode IDE 和 iOS SDK。
- Android:可在 Windows 上开发,需要 Windows 7 或更新版本、Java SDK、Android SDK 和 Xamarin.Android for Visual Studio。
- Windows Phone:需 Windows 7 或更新版本及 Visual Studio。
使用Xamarin Forms开始编程
开发人员可在 Xamarin Studio 或 Visual Studio 中创建 Xamarin.Forms 项目,有四种项目类型可选:Portable Library(用于代码共享)、Xamarin.Android Application、Xamarin.iOS Application 和 Windows Phone Application。在 Xamarin Studio 中,通过选择 File > New > Solution,点击 C# > Mobile Apps,然后选择 Blank App (Xamarin.Forms Portable) 来创建新项目。
Xamarin.Forms 应用程序
Xamarin.Forms 中每个屏幕对应一个 Page 概念,如 ContentPage,在安卓中与 Activity 对应,在 iOS 中与 ViewController 对应。应用初始化时,App 类负责设置首页。例如,以下代码创建一个 ContentPage,并添加一个居中的 Label 控件:
public class App
{
public static Page GetMainPage()
{
return new ContentPage
{
Content = new Label
{
Text = "Hello, Forms!",
VerticalOptions = LayoutOptions.CenterAndExpand,
HorizontalOptions = LayoutOptions.CenterAndExpand,
},
};
}
}
在不同平台上,需初始化 Xamarin.Forms 框架并设置页面:
- Android:在 MainActivity 的 OnCreate 方法中调用
Xamarin.Forms.Forms.Init并设置页面。 - iOS:在 AppDelegate 的 FinishedLaunching 方法中初始化并设置 RootViewController。
- Windows Phone:在 MainPage 构造函数中初始化并设置 Content。
视图与布局
Xamarin.Forms 使用控件构建UI,常见类型包括 View(如 Label、Button)、Page、Layout 和 Cell。布局容器有两种类型:Managed Layout(如 StackLayout,通过设定子控件位置和大小自动布局)和 Unmanaged Layouts(如 AbsoluteLayout,需手动设定位置和大小)。
堆栈式布局
StackLayout 是常用布局方式,子元素按添加顺序摆放,方向可为竖直或水平。例如,创建三个 Label 控件并添加到 StackLayout:
public class StackLayoutExample : ContentPage
{
public StackLayoutExample()
{
Padding = new Thickness(20);
var red = new Label { Text = "Stop", BackgroundColor = Color.Red, Font = Font.SystemFontOfSize(20) };
var yellow = new Label { Text = "Slow down", BackgroundColor = Color.Yellow, Font = Font.SystemFontOfSize(20) };
var green = new Label { Text = "Go", BackgroundColor = Color.Green, Font = Font.SystemFontOfSize(20) };
Content = new StackLayout
{
Spacing = 10,
Children = { red, yellow, green }
};
}
}
通过 XAML 也可实现类似布局。默认方向为竖直;改为水平方向需设置 Orientation = StackOrientation.Horizontal。子元素可通过 HeightRequest 和 WidthRequest 指定大小。
绝对布局
AbsoluteLayout 需指定每个子元素的位置。例如,添加多个 Label 到 AbsoluteLayout 并设置坐标:
public class MyAbsoluteLayoutPage : ContentPage
{
public MyAbsoluteLayoutPage()
{
var red = new Label { Text = "Stop", BackgroundColor = Color.Red, Font = Font.SystemFontOfSize(20), WidthRequest = 200, HeightRequest = 30 };
var yellow = new Label { Text = "Slow down", BackgroundColor = Color.Yellow, Font = Font.SystemFontOfSize(20), WidthRequest = 160, HeightRequest = 160 };
var green = new Label { Text = "Go", BackgroundColor = Color.Green, Font = Font.SystemFontOfSize(20), WidthRequest = 50, HeightRequest = 50 };
var absLayout = new AbsoluteLayout();
absLayout.Children.Add(red, new Point(20, 20));
absLayout.Children.Add(yellow, new Point(40, 60));
absLayout.Children.Add(green, new Point(80, 180));
Content = absLayout;
}
}
子元素添加顺序影响 Z-Order,后添加的元素可能遮住先添加的元素。
列表
ListView 用于展现数据列表,每个条目包含在单元格内。默认使用 TextCell 作为模板。例如,绑定字符串数组到 ListView:
var listView = new ListView { RowHeight = 40 };
listView.ItemsSource = new string[] { "Buy pears", "Buy oranges", "Buy mangos", "Buy apples", "Buy bananas" };
Content = new StackLayout { VerticalOptions = LayoutOptions.FillAndExpand, Children = { listView } };
可绑定自定义数据类型,如 TodoItem 类,并通过 DataTemplate 设置显示属性。ItemSelected 事件处理条目选择,用于导航或显示详情。
自定义单元格样式
ListView 支持自定义单元格样式,例如创建包含 Image 和多个 Label 的布局。通过继承 ViewCell 并定义控件,然后绑定数据源。XAML 也可实现类似功能,使用 DataTemplate 和绑定表达式。
数据绑定
数据绑定允许控件展示和编辑数据层数据。在页面构造函数中设置 BindingContext 并绑定属性,例如将 Employee 对象的属性绑定到 Entry 控件:
public EmployeeDetailPage(Employee employeeToDisplay)
{
this.BindingContext = employeeToDisplay;
var firstName = new Entry() { HorizontalOptions = LayoutOptions.FillAndExpand };
firstName.SetBinding(Entry.TextProperty, "FirstName");
}
页面导航
页面导航基于堆栈结构,使用 INavigation 接口。NavigationPage 实现该接口并在顶部添加导航条。通过 PushAsync 方法添加新页面,PopAsync 方法返回上一页。模态对话框使用 PushModalAsync 和 PopModalAsync。例如,从列表页导航到详情页:
listView.ItemSelected += async (sender, e) => {
var todoItem = (TodoItem)e.SelectedItem;
var todoPage = new TodoItemPage(todoItem);
await Navigation.PushAsync(todoPage);
};
小结
本文介绍了 Xamarin.Forms 的基本概念和开发流程,包括安装、项目创建、控件使用、布局管理、数据绑定和页面导航。Xamarin.Forms 提供了一种高效的方式构建跨平台移动应用,通过共享代码减少开发工作量。