Binding a Xamarin.Forms WebView to ReactiveUI View Model using Custom Type Converters
Introduction
In this article, we will expand on our demo app, by displaying article content inside of a WebView after the user is navigated to the ArticleView.
To make things more interesting, because we are pulling in content from this blog, we will be using HTMLAgilityPack to strip out any unnecessary HTML that we don't want to be displayed inside of our app.
We'll also be utilising a ReactiveUI custom type converter to bind our WebView to raw HTML content.
At a high level our ArticleViewModel is going to do the following:
- Download HTML from URL specified in the Article object that we are storing in our ViewModel
- Cache the HTML content
- Parse HTML to strip out unwanted tags, and fix other related issues
- Map content to WebView
Setup
Install the HTMLAgilityPack NuGet package into all three projects i.e. Droid, iOS, and PCL projects. We'll be using this to clean up the HTML that we download from this blog.
https://www.nuget.org/packages/HtmlAgilityPack
Parsing HTML
A WebView can take two different data sources, the first being a website URL, and the second being a raw HTML string. In our case we want to use the second method, this is because we'd like to modify the HTML from the articles before we display the article in our View.
I won't go into the parsing code detail, but at a high level, you can see what is happening in the code snippet below.
public interface IHtmlParserService
{
string Parse(string content, string baseUrl);
}
public class HtmlParserService : IHtmlParserService
{
public string Parse(string content, string baseUrl)
{
var document = new HtmlDocument();
document.LoadHtml(content);
ReplaceRelativeUrls(document, baseUrl);
RemoveRedundantElements(document);
return document.DocumentNode.OuterHtml;
}
...
}
The full source code for this class can be found here.
ViewModel
We'll now setup our ViewModel. The first thing we need to do is create a new property that the View will bind to called Content. This property will simply store the parsed HTML content that we want to display in our View.
string _content;
public string Content {
get => _content;
set => this.RaiseAndSetIfChanged(ref _content, value);
}
We now need to implement our methods for fetching our content from the blog, and also the method that we'll use to map the parsed HTML content to our Content property.
IObservable<string> LoadArticleContent()
{
return BlobCache
.LocalMachine
.GetOrFetchObject<string>
(CacheKey,
async () =>
await _articleService.Get(Article.Url), CacheExpiry);
}
void MapContentImpl(string content)
{
Content = _htmlParserService.Parse(content, Configuration.BlogBaseUrl);
}
We now want to call our new LoadArticleContent method from inside of our constructor to initialize the Content property that the View will be bound to.
public ArticleViewModel(IScreen hostScreen, Article article)
{
...
LoadArticleContent()
.ObserveOn(RxApp.MainThreadScheduler)
.Catch<string, Exception>((error) => {
this.Log().ErrorException($"Error loading article {Article.Id}", error);
return Observable.Return("<html><body>Error loading article.</body></html>");
})
.Subscribe(MapContentImpl);
}
The above code simply does the following:
- Call LoadArticleContent method
- Ensure that the following code runs on the main UI thread
- Catch any exceptions, and return an error message
- Call the MapContentImpl method and pass the result of LoadArticleContent or the Error message
Custom Type Converters
Now that our ViewModel is all setup, we just need to bind the Source property of our WebView to our Content property on our ViewModel.
Because the Source property of a WebView uses a type that doesn't have a default binding converter provided by ReactiveUI, we'll need to create our own.
To do this we just need to create a class that implements the IBindingTypeConverter interface.
public class HtmlBindingTypeConverter : IBindingTypeConverter, IEnableLogger
{
public int GetAffinityForObjects(Type fromType, Type toType)
{
return fromType == typeof(string) && toType == typeof(WebViewSource) ? 100 : 0;
}
public bool TryConvert(object from, Type toType, object conversionHint, out object result)
{
try
{
result = new HtmlWebViewSource { Html = (string)from };
return true;
}
catch (Exception error)
{
this.Log().ErrorException("Problem converting to HtmlWebViewSource", error);
result = null;
return false;
}
}
}
The GetAffinityForObjects method simply validates that a the from and to properties can be converted by our type converter. If it can't then we should return 0 otherwise, we should return any number greater than 0. If there are two converters that can handle the types that are passed to it, then the number returned by this method will determine which one is selected.
The TryConvert method does the actual conversion from one type to another.
You can read more about type converters here:
https://reactiveui.net/docs/handbook/data-binding/type-converters
Now that we have created our type converter, we need to register it with the Splat dependency resolver. We do this in our AppBootstrapper class.
public class AppBootstrapper : ReactiveObject, IScreen
{
...
private void RegisterParts(IMutableDependencyResolver dependencyResolver)
{
...
dependencyResolver.RegisterConstant(new HtmlBindingTypeConverter(), typeof(IBindingTypeConverter));
}
...
}
Binding the View
All we need to do now is setup the binding in our view.
public partial class ArticlePage : ContentPage, IViewFor<ArticleViewModel>
{
readonly CompositeDisposable _bindingsDisposable = new CompositeDisposable();
...
protected override void OnAppearing()
{
base.OnAppearing();
this.OneWayBind(ViewModel, vm => vm.Content, v => v.ArticleContent.Source).DisposeWith(_bindingsDisposable);
}
...
}
Summary
In this article, we've created a custom type converter for binding raw HTML content to a Xamarin.Forms WebView.
Full source code for this article can be found here:
https://github.com/jamilgeor/FormsTutor/tree/master/Lesson09
References
https://www.nuget.org/packages/HtmlAgilityPack
https://reactiveui.net/docs/handbook/data-binding/type-converters
Binding a Xamarin.Forms WebView to ReactiveUI View Model using Custom Type Converters的更多相关文章
- Xamarin.Forms——WebView技术研究
在Xamarin中有一些Forms原生不太好实现的内容可以考虑使用HTML.Javascript.CSS那一套前端技术来实现,使用WebView来承载显示本地或网络上的HTML文件.不像OpenUri ...
- Xamarin.Forms WebView
目前本地或网络的网页内容和文件加载 WebView是在您的应用程序显示Web和HTML内容的视图.不像OpenUri,这需要用户在Web浏览器的设备上,WebView中显示您的应用程序内的HTML内容 ...
- Xamarin Forms中WebView的自适应高度
在Xamarin.Forms中,WebView如果嵌套在StackLayout和RelativeLayout中必须要设置HeightRequest和WidthRequest属性才会进行渲染.可是在实际 ...
- 在 Xamarin.Forms 实现密码输入EntryCell
在 Xamarin.Forms 中,我们通常使用 TableView 来构建输入表单.Xamarin 为我们提供了 EntryCell 用于输入文本,但是其并不支持密码输入,即密码掩码.这里要对 En ...
- Xamarin.Forms 自定义控件(呈现器和效果)
Xamarin.Forms 使用目标平台的本机控件呈现用户界面,从而让 Xamarin.Forms 应用程序为每个平台保留了相应的界面外观.凭借效果,无需进行自定义呈现器实现,即可自定义每个平台上的本 ...
- 搞懂Xamarin.Forms布局,看这篇应该就够了吧
Xamarin.Forms 布局介绍 什么是布局?可以简单的理解为,我们通过将布局元素有效的组织起来,让屏幕变成我们想要的样子! 我们通过画图的方式来描述一下Xamarin.Forms的布局. 小节锚 ...
- Xamarin.Forms介绍
On May 28, 2014, Xamarin introduced Xamarin.Forms, which allows you to write user-interface code tha ...
- Xamarin.Forms中为WebView指定数据来源Source
Xamarin.Forms中为WebView指定数据来源Source 网页视图WebView用来显示HTML和网页形式内容.使用这种方式,可以借助网页形式进行界面设计,并利于更新和维护.WebVi ...
- Xamarin.Forms 开发资源集合(复制)
复制:https://www.cnblogs.com/mschen/p/10199997.html 收集整理了下 Xamarin.Forms 的学习参考资料,分享给大家,稍后会不断补充: UI样式 S ...
随机推荐
- 实现动态WEB内容
在 system1 上配置提供动态web内容,要求: 1.动态内容由名为 wsgi.group8.example.com 的虚拟主机提供 2.虚拟主机侦听在端口 8909 3.从 http://ser ...
- elasticsearch安全重启节点
elasticsearch集群,有时候可能需要修改配置,增加硬盘,扩展内存等操作,需要对节点进行维护升级.但是业务不能停,如果直接kill掉节点,可能导致数据丢失.而且集群会认为该节点挂掉了,就开始转 ...
- [cf 1245 F] Daniel and Spring Cleaning
题意: 求区间$[l,r]$内有多少有序数对$(a,b)$满足$a+b=a\bigoplus b$. $l,r\leq 10^9$. 题解: 有用的就一句话: 求区间内一元组可以一维容斥,同理求二元组 ...
- phpdocmentor 生成php 开发文档(转载)
PHPDocumentor是一个用PHP写的工具,对于有规范注释的php程序,它能够快速生成具有相互参照,索引等功能的API文档.老的版本是phpdoc,从1.3.0开始,更名为phpDocument ...
- .net Dapper 实践系列(1) ---项目搭建(Layui+Ajax+Dapper+MySQL)
目录 写在前面 一.前期准备 1.在MySQL创建数据库 2.创建项目 3.安装程序包 4.添加插件 5.添加DbOption文件夹 6.添加实体类 写在前面 学习并实践使用Dapper 这个小型的O ...
- MVC学习笔记(一)—用EF创建数据库
1.新建MVC项目 2.在Models文件夹下添加名为User的新类 2.1 Users类中的代码为: public class Users { /// <summary> / ...
- 知识扩展——(转)一篇文章彻底弄懂Base64编码原理
在互联网中的每一刻,你可能都在享受着Base64带来的便捷,但对于Base64的基础原理又了解多少?今天这篇博文带领大家了解一下Base64的底层实现. 一.Base64的由来 目前Base64已经成 ...
- 使用FMXlinux 开发linux 桌面应用
自从delphi 10.2 开始正式支持linux 开发来,大家一直关心为什么官方没有使用FMX来支持LInux 的桌面开发? 其实原因无非就几点: 1.Linux 大部分是应用还是服务端的,桌面应 ...
- PHP 两个比较运算符 [??] [?:] 差别
1.[??] NULL 合并操作符$a ?? $b即isset($a) ? $a : $b; 注:isset() 已设置并且不为NULL 2.[?:] 三元运算符的简写形式$a ?: $b即$a ? ...
- Redis相关知识整理
Redis相关知识整理 1. Redis和MySQL的区别?a).mysql是关系型数据库,而redis是NOSQL,非关系型数据库.mysql将数据持久化到硬盘,读取数据慢,而redis数据先存储在 ...