Xamarin MVVM

定义一个 ViewModel :

using System.ComponentModel;
using System.Net.Http;
using System.Threading.Tasks;
using System.Windows.Input;
using Xamarin.Forms;

namespace poetry.ViewModels
{
    public class DataViewModel: INotifyPropertyChanged
    {
        private readonly HttpClient _client = new HttpClient();
        public DataViewModel()
        {
            _name = "curry";
            ChangeNameCommand = new Command<string>((key) =>
            {
                Name = key;
            });
            Task.Run(async () =>
            {
                var response = await _client.GetAsync("https://poetrydev.lightfly.cn/");
                response.EnsureSuccessStatusCode();
                var body = await response.Content.ReadAsStringAsync();
                Name = body;
            });
        }

        public event PropertyChangedEventHandler PropertyChanged;

        private string _name;

        public string Name
        {
            get => _name;
            set
            {
                _name = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Name"));
            }
        }

        public ICommand ChangeNameCommand { protected set; get; }
    }
}

MVVM 模式, View -> ViewModel -> Model . View 中的响应式数据对应于 ViewModel 中的 class 属性,View 中的 action 对应于 ViewModel 中的 Command。 ViewModel 继承自 INotifyPropertyChanged, 这里的响应式属性需要显示定义,对应于代码:

public string Name
        {
            get => _name;
            set
            {
                _name = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Name"));
            }
        }

PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Name")); 通知 View 属性的变更进行界面刷新。Command 中定义业务逻辑,对 ViewModel 中的属性变更来刷新界面。

在页面中绑定 ViewModel :

 <ContentPage.BindingContext>
        <viewModels:DataViewModel />
    </ContentPage.BindingContext>