使用 Xamarin Forms 与 Prism、解耦 UI 和测试 - 第一部分
第一部分介绍 Prism 和 Xamarin Forms 的设置
引言
在创建了许多 Xamarin 应用之后,我学到了很多,并且想分享我认为开始 Xamarin 项目的更好的方法。
有很多方法可以开发 Xamarin Forms (XF) 应用,例如使用 MVVMCross(我最喜欢的)、MvvmLight 等。我选择使用 Microsoft Prism,因为它在 WPF 和 Windows mobile 世界中经过了充分的测试。这只是我个人选择使用 Prism。
Prism 支持 MVVM、命令、消息传递、事件聚合等等。
我要感谢 Brian Lagunas,因为我从他的讲座中学到了 Prism 的大部分知识。
背景
以下是我在开发 Xamarin Forms 应用时喜欢使用的一些内容:
- MVVM 模式
- XF 命令
- 外观模式
- 仓库模式
- Prism - IOC
- 使用 C# 构建 UI
Using the Code
我喜欢用尽可能少的文字来解释,所以我会尽量给出更多的要点和代码。
- 显然,创建一个 Xamarin 默认项目。
- 安装 NuGet 包,例如
Prism
、Prism.Forms
、Prism.Unity.Forms
。 - 我喜欢用 C# 编写 Xamarin Forms 页面 UI。在 Views 文件夹下添加一个主页。重要的是,我们必须将页面文件夹命名为 Views,因为 Prism 会尝试在此文件夹中查找页面。
AutowireViewModelProperty
设置为true
,这意味着我们告诉页面自动选择ViewModel
并将其绑定上下文设置为相同的ViewModel
。public class Home : ContentPage { public Home() { SetValue(ViewModelLocator.AutowireViewModelProperty, true); var label = new Label { Text = "Hello ContentPage" }; label.SetBinding<HomeViewModel>(Label.TextProperty, v => v.Name); Content = new StackLayout { Children = { label } }; } }
- 在 ViewModels 文件夹下添加一个 ViewModel 类,将其命名为
pagename
并附加单词ViewModel
。同样,重要的是将文件夹命名为 ViewModels。- 例如,如果
Page
命名为HomePage
,则将ViewModel
命名为HomePageViewModel
- 例如,如果
- 如您所见,
HomeViewModel
继承自BindableBase
。它帮助属性调用INotifyableProperty
,仅此而已。public class HomeViewModel : BindableBase { private string _name = "Divikiran Ravela"; public string Name { get { return _name; } set { SetProperty(ref _name, value); } } public HomeViewModel() { } }
- 创建一个公共文件夹并添加一个类文件,并将其命名为 Bootstrapper,下面显示了最简单的形式:
public class Bootstrapper : UnityBootstrapper { protected override Page CreateMainPage() { return Container.Resolve<Home>(); } protected override void RegisterTypes() { Container.RegisterType<HomeViewModel>(); } }
- 现在转到 App.cs 并添加如下所示的代码,如您所见,我们的
Bootstrapper
类被实例化,并且应用程序作为参数传递给Run
方法。这将触发CreateMainPage
并调用第一个页面。public Bootstrapper Bootstrapper { get; set; } public App() { // The root page of your application Bootstrapper = new Bootstrapper(); Bootstrapper.Run(this); } protected override void OnStart() { // Handle when your app starts } protected override void OnSleep() { // Handle when your app sleeps } protected override void OnResume() { // Handle when your app resumes } }
请查找附件中的代码以查看应用程序的运行情况。
如有任何疑问,请随时提问。我会尽力回答。
接下来,在第二部分中,我将尝试解释使用 C# 和 Facade 模式解耦 UI。
该代码也可在 https://github.com/divikiran/XamarinWithPrism 上找到。