MVVM Model-View-ViewModel
数据 视图(看) 干活
VUE Angular React MINA都是MVVM
暂时认为View和ViewModel一一对应
思路:业务和UI分离:
1. View:MainPage.xaml——>绑定Result和ClickMeCommand
2. MainPageViewModel.cs——>提供数据Result和功能Command
3. 使用定位器模式ViewModelLocator.cs——>定位ViewModel(依赖注入容器SimpleIoc)
4. 将ViewModelLocator注册在全局App.xaml里
5. 在MainPage里通过ViewModelLocator绑定MainPageViewModel
-
MainPageViewModel.cs
public class MainPageViewModel : ViewModelBase
{
private string _result;
public string Result
{
get => _result;
set => Set(nameof(Result), ref _result, value);
}
/*值可读可写 数据可为空
如果想读Result属性 那么返回_result给他
如果想写Result属性 nameof(Result)将Result转换成字符串
ref _result按引用传递
value表示赋过去的值
写在_result里
_result和Result关系 类似于Java的get、set*/
private RelayCommand _clickMeCommand;
public RelayCommand ClickMeCommand =>
_clickMeCommand ?? (_clickMeCommand =
new RelayCommand(() => Result = "Hello World!"));
/*命令只读 命令不能为空
把Result变成"Hello World!"
若_clickMeCommand为空则执行括号*/
}
//ViewModel的本质:提供 数据Result 和 功能Command
-
定位器模式ViewModelLocator.cs
namespace HelloWorld.ViewModels
{
public class ViewModelLocator
{//定位器能定位 负责找ViewModel
public MainPageViewModel MainPageViewModel =>
SimpleIoc.Default.GetInstance<MainPageViewModel>();
//依赖注入容器 SpringIoc
public ViewModelLocator()
{//定位器
SimpleIoc.Default.Register<MainPageViewModel>();
//只要注册一下,以后可以无限取
}
}
}
-
App.xaml
<Application xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:vm="clr-namespace:HelloWorld.ViewModels;assembly=HelloWorld"
//引入HelloWorld.ViewModels命名空间
x:Class="HelloWorld.App">
<Application.Resources>
<vm:ViewModelLocator x:Key="ViewModelLocator" />
//注册ViewModelLocator资源
</Application.Resources>
</Application>
-
MainPage.xaml
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
BindingContext="{Binding MainPageViewModel, Source={StaticResource ViewModelLocator}}"//从ViewModelLocator绑定MainPageViewModel
x:Class="HelloWorld.MainPage">
<StackLayout>
<Label Text="{Binding Result}"></Label>//将Text绑定到Result
<Button Command="{Binding ClickMeCommand}"></Button>//将Command绑定到ClickMeCommand
//使业务和UI分离
</StackLayout>
</ContentPage>