MAUI使用MVVM代码步骤
1、安装nuget包 CommunityToolkit.Mvvm
2、新建ViewModel类
public class UserViewModel : ObservableObject { private UserModel _userModel; private string _username; private string _password; private ICommand _btnLogin; private ICommand _btnAdd; private ICommand _btnResetPwd; public string UserName { get => _username; set => SetProperty(ref _username, value); } public string Password { get => _password; set => SetProperty(ref _password, value); } public ICommand BtnLogin { get => _btnLogin ?? (_btnLogin = new RelayCommand(BtnLoginCallback)); } public ICommand BtnAdd { get => _btnAdd ?? (_btnAdd = new RelayCommand(BtnAddCallback)); } public ICommand BtnResetPwd { get => _btnResetPwd ?? (_btnResetPwd = new RelayCommand(BtnResetPwdCallback)); } private void BtnLoginCallback() { Console.WriteLine("Login"); Shell.Current.GoToAsync("//SecretManager"); } private void BtnAddCallback() { Console.WriteLine("add"); } private void BtnResetPwdCallback() { Console.WriteLine("reset"); } public void ApplyQueryAttributes(IDictionary<string, object> query) { if (query.ContainsKey("")) { RefreshProperties(); } } private void RefreshProperties() { OnPropertyChanged(nameof(UserModel)); } }
3、新建IOC服务类 ServiceLocator
public class ServiceLocator { private IServiceProvider _serviceProvider; public UserViewModel UserViewModel=>_serviceProvider.GetService<UserViewModel>(); public ServiceLocator() { var serviceCollection=new ServiceCollection(); serviceCollection.AddSingleton<UserViewModel>();//视图注册到容器内,就不用new对象 _serviceProvider= serviceCollection.BuildServiceProvider(); } }
4、App.xaml配置页面调用ViewModel服务类
<ResourceDictionary> <local:ServiceLocator x:Key="ServiceLocator"/> </ResourceDictionary>
5、ViewModel绑定
BindingContext="{Binding UserViewModel, Source={StaticResource ServiceLocator}}"
6、使用ViewModel中定义的对象或事件
Text="{Binding UserName}"/>
本文来自博客园,作者:CelonY,转载请注明原文链接:https://www.cnblogs.com/CelonY/p/17824320.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 提示词工程——AI应用必不可少的技术
· 地球OL攻略 —— 某应届生求职总结
· 字符编码:从基础到乱码解决
· SpringCloud带你走进微服务的世界
2020-11-10 identityserver4