首先,講一下什么是 ReactiveProperty, 簡(jiǎn)單的講,就是可以實(shí)現(xiàn) View 和 ViewModel 之間的雙向綁定,當(dāng) View 中某一部分UI的數(shù)據(jù)發(fā)生變化時(shí),ReactiveProperty 可以實(shí)時(shí)的把這種變化反映到 layout 中。它支持 MVVM 和異步。
作為 ReactiveProperty 的入門,我準(zhǔn)備先寫一個(gè)簡(jiǎn)單的 sample 為樣例。 ( 這東西好不好用,先入門了再說 )
1.要使用 ReactiveProperty ,需要先在 Xamarin 工程中添加 ReactiveProperty 的 Package。

ReactiveProperty.png
- 接下來新建 sample 的 layout 文件,ReactivePage.xaml 如下:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="TutorialApp.Views.ReactivePage">
<ContentPage.Content>
<StackLayout>
<Entry Text="{Binding Input.Value}"/>
<Label Text="{Binding Output.Value}" />
</StackLayout>
</ContentPage.Content>
</ContentPage>
layout 中包括一個(gè) Entry 和一個(gè) Label。一個(gè)輸入文字,一個(gè)顯示文字。
- 開始新建 ViewModel ,代碼如下:
using Reactive.Bindings;
using System;
using System.Reactive.Linq;
using Xamarin.Forms;
namespace TutorialApp.ViewModel
{
public class ReactivePageViewModel : ContentPage
{
public ReactiveProperty<string> Input { get; }
public ReactiveProperty<string> Output { get; }
public ReactivePageViewModel()
{
Input = new ReactiveProperty<string>("");
Output = Input
.Delay(TimeSpan.FromSeconds(1)) // Using a Rx method.
.Select(x => x.ToUpper()) // Using a LINQ method.
.ToReactiveProperty(); // Convert to ReactiveProperty
}
}
}
看 ViewModel 中處理。顯然, 就是把 Input 輸入的字符串 延遲一秒,小寫轉(zhuǎn)大寫后表示出來。
實(shí)現(xiàn)的效果請(qǐng)看下面的 gif 圖。

reactive.gif
可以看到圖片中 第二行 延遲一秒,把小寫字符都轉(zhuǎn)成大寫后表示了出來。
這只是一個(gè)簡(jiǎn)單的入門樣例,不過由這個(gè)樣例,我們可以發(fā)現(xiàn)有很多地方可以用 ReactiveProperty 去實(shí)現(xiàn)。例如:APP 登錄用的賬號(hào)和密碼的 check、listview 中數(shù)據(jù)的添加和刪除。
有關(guān)更多的應(yīng)用場(chǎng)景,可以一起交流喔。
以上。