Binding Navigated Event in WebView Control

WebView Control in Xamarin.Form is a highly useful control for displaying a Web Page within your Mobile Application. You can either specify the URI that needs to displayed or you can provide the entire HTML Source to be displayed by assigning an instance of UrlWebViewSource to the Source Property of the control.

From an MVVM point of view, you can bind Source Property of the control to an instance of UrlWebViewSource.
<WebView Source="{Binding GatewayPageSource,Mode=TwoWay}" WidthRequest="500" HeightRequest="500"></WebView>

For Binding the control to an External URI, you could bind your ViewModel Property as follows.


public HtmlWebViewSource GatewayPageSource
 {
 get { return _GateWaySource; }
 set
 {
 SetProperty(ref _GateWaySource, value);
 }
 }

this.GatewayPageSource.BaseUrl = "urlpath";

For Binding the control to an HTML String, you could bind your ViewModel Property as follows.


this.GatewayPageSource.Html = "HtmlString"

One of the caveats however, is that two of the most important Events of the control, namely, Navigating and Navigated, is not Bindable. There are ways to get around this problem though.
The first method that was suggested to me was to use Behavior. I will probably try implementing this in one of later posts. The second approach, was possibly the easiest – create a custom control overriding the WebView and add the required properties.
public class AdvancedWebView : WebView
{
public static readonly BindableProperty NavigatedCommandProperty =
BindableProperty.Create(nameof(NavigatedCommand), typeof(ICommand), typeof(AdvancedWebView), null);

public AdvancedWebView()
{
Navigated += (s, e) =>
{
if (NavigatedCommand?.CanExecute(e) ?? false)
NavigatedCommand.Execute(e);
};
}

public ICommand NavigatedCommand
{
get { return (ICommand)GetValue(NavigatedCommandProperty); }
set { SetValue(NavigatedCommandProperty, value); }
}
}

The XAML with new Control would be as follows


<controls:AdvancedWebView Source="{Binding GatewayPageSource,Mode=TwoWay}"
NavigatedCommand="{Binding WebViewNavigatedCommand}"
WidthRequest="500" HeightRequest="500"/>

For keeping things simple, I have implemented only Navigated Event in the example, however, we could extend this functionality with Navigating Event as well.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s