美文网首页
在 xamarin.forms 中使用 ReactiveProp

在 xamarin.forms 中使用 ReactiveProp

作者: 你喜欢的蓝 | 来源:发表于2020-03-09 23:05 被阅读0次

首先,讲一下什么是 ReactiveProperty, 简单的讲,就是可以实现 View 和 ViewModel 之间的双向绑定,当 View 中某一部分UI的数据发生变化时,ReactiveProperty 可以实时的把这种变化反映到 layout 中。它支持 MVVM 和异步。

作为 ReactiveProperty 的入门,我准备先写一个简单的 sample 为样例。 ( 这东西好不好用,先入门了再说 )


1.要使用 ReactiveProperty ,需要先在 Xamarin 工程中添加 ReactiveProperty 的 Package。


ReactiveProperty.png
  1. 接下来新建 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 中包括一个 Entry 和一个 Label。一个输入文字,一个显示文字。

  1. 开始新建 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 输入的字符串 延迟一秒,小写转大写后表示出来。

实现的效果请看下面的 gif 图。

reactive.gif
可以看到图片中 第二行 延迟一秒,把小写字符都转成大写后表示了出来。

这只是一个简单的入门样例,不过由这个样例,我们可以发现有很多地方可以用 ReactiveProperty 去实现。例如:APP 登录用的账号和密码的 check、listview 中数据的添加和删除。

有关更多的应用场景,可以一起交流喔。

以上。

相关文章

网友评论

      本文标题:在 xamarin.forms 中使用 ReactiveProp

      本文链接:https://www.haomeiwen.com/subject/elomdhtx.html