Home > C#, MVVM, WinRT > How to use binding to set the WebView Url in a Windows Store app

How to use binding to set the WebView Url in a Windows Store app


The WebView control that is part of WinRT doesn’t expose a property to directly set the Url that we want to navigate to. Instead, we need to use the Navigate method. This is annoying if we’re using the MVVM pattern.

So, a possible solution is to define an attached property that allow us to specify the Url via binding. Take a look to the following class:

public static class WebViewExtensions
    public static string GetUriSource(WebView view)
        return (string)view.GetValue(UriSourceProperty);

    public static void SetUriSource(WebView view, string value)
        view.SetValue(UriSourceProperty, value);

    public static readonly DependencyProperty UriSourceProperty = 
        "UriSource", typeof(string), typeof(WebViewExtensions), 
        new PropertyMetadata(null, OnUriSourcePropertyChanged));

    private static void OnUriSourcePropertyChanged(DependencyObject sender, 
        DependencyPropertyChangedEventArgs e)
        var webView = sender as WebView;
        if (webView == null)
            throw new NotSupportedException();

        if (e.NewValue != null)
            var uri = new Uri(e.NewValue.ToString());

We’re defining a new Dependecy Property, UriSource, that, when set, simply calls the Navigate method on the WebView. In this way, in our XAML file we can write something like this:

    local:WebViewExtensions.UriSource="{Binding ItemUrl}" />

To create a binding between the WebView Url and a property called ItemUrl on our model.

Categories: C#, MVVM, WinRT
%d bloggers like this: