学习笔记(Maui-HelloWorld)
- 1 包下载镜像(中国本地)设置
- 2 MVVM in Maui
- 2.1 安装MVVM包
- 2.2 ViewModel 属性定义
- 2.3 View 与 ViewModel 的连接
- 2.3.1 服务定位器模式
- 2.3.2 Resource
- 2.3.3 View 绑定
- 3 文档提供的方法
- 3.1 依赖注入
- 3.1.1 依赖注入的注入实现
- 3.1.2 依赖注入的解析实现
- 3.2 MVVM
文章是东北大学张引老师.NET MAUI全栈开发技术课程的学习笔记。原课程对初学者比较友好,但是细节太多,很难完全记住。记笔记是为了使用技术时细节有可查之处,也方便和同道讨论。
1 包下载镜像(中国本地)设置
工具 --> 选项 --> NuGet包管理器 --> 程序包源 --> + --> https://nuget.cdn.azure.cn/v3/index.json -->更新 --> 确定
镜像设置不是必须的,似乎不改变下载速度也可以
2 MVVM in Maui
2.1 安装MVVM包
Nuget 安装 CommunityToolkit.Mvvm
2.2 ViewModel 属性定义
ViewModel 需要继承自 ObservableObject
private string _Example;
public string Example
{
get => _Example;
set => SetProperty(ref _Example, value);
}
private RelayCommand _CommandExample;
public RelayCommand CommandExample => _CommandExample ??= new RelayCommand(()=>
{
// do something here!
});
2.3 View 与 ViewModel 的连接
2.3.1 服务定位器模式
项目中添加类 ServiceLocator
public class ServiceLocator
{
private IServiceProvider _ServiceProvider;
public ViewModelMainPage ViewModelMainPage=>_ServiceProvider.GetService<ViewModelMainPage>();
public ServiceLocator()
{
ServiceCollection serviceCollection = new ServiceCollection();
serviceCollection.AddSingleton<ViewModelMainPage>();
_ServiceProvider = serviceCollection.BuildServiceProvider();
}
}
2.3.2 Resource
在文件 App.xaml 中将 ServiceLocator 注册为资源,具体为在标签 <ResourceDictionary.MergedDictionaries>
内添加 ServiceLocator 资源标签。
<ResourceDictionary>
<local:ServiceLocator x:Key="ServiceLocator"/>
</ResourceDictionary>
local 指本项目的命名空间
2.3.3 View 绑定
在文件 MainPage.xaml 中,ContentPage 标签配置部分完成绑定。
BindingContext="{Binding ViewModelMainPage, Source={StaticeResource ServiceLocator}}"
View 中的绑定是常规做法,这里略过。
3 文档提供的方法
Maui 的官方文档给出的依赖注入和MVVM的实现方法与张老师提供的方法有所不同,列在下面供参考。以下代码参考微软 Maui 官方文档。
3.1 依赖注入
3.1.1 依赖注入的注入实现
在文件 MauiProgram.cs 中,使用已经被系统定义的 MauiAppBuilder 类型变量 builder 进行依赖注入的注入实现。
builder.Services.AddSingleton<ViewModelMainPage>();
builder.Services.AddSingleton<MainPage>();
3.1.2 依赖注入的解析实现
依赖注入的解析有2种方法。
第一种依赖解析方法使用构造函数,自动依赖项解析,这种方法最常用。
public MainPage(ViewModelMainPage viewModelMainPage)
{
InitializeComponent();
this.BindingContext = viewModelMainPage;
}
第二种依赖解析方法使用全局变量,显式依赖项解析。
public MainPage( )
{
InitializeComponent();
this.BindingContext = Application.Current.MainPage.Handler.MauiContext.Services.GetService<ViewModelMainPage>();
}
3.2 MVVM
官方文档 MVVM 没有用 CommunityToolkit.MVVM 包,ViewModel 直接实现 INotifyPropertyChanged 接口。在 Xaml 文件对应的 cs 文件中显示地实现绑定。可以使用依赖注入,也可已不使用,使用的版本已经在上面提供了,下面是不使用的。
public MainPage()
{
InitializeComponent();
this.BindingContext = new ViewModelMainPage();
}