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}"/>