东北大学全栈开发课程笔记1

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>

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值