Bind WebView2 to ViewModel Using Caliburn Micro

Viewed 1696

I am using the guide located her for reference: https://docs.microsoft.com/en-us/microsoft-edge/webview2/gettingstarted/wpf

Utilizing that guide, I was able to get WebView2 started within my application. Now I am trying to seperate the code into a ViewModel as I will have many more elements on that page. The application as a whole uses Caliburn Micro. I am able to bind everything to the ViewModel except for the WebView2 itself. Wheneer I Select the Go button it states that the WebView is null. I tried manually setting the WebView however that does not work.

BrowserView.xaml:

    <Button 
            x:Name="ButtonGo" 
            Content="Go"
            />
        <TextBox x:Name = "Addressbar"
                 />
    <wv2:WebView2 x:Name = "WebView"
                  Source="{Binding WebViewSource}"
/>

BrowserViewModel.cs

        private WebView2 _webView;

    public WebView2 WebView
    {
        get 
        {
            return _webView; 
        }
        set 
        {
            _webView = value;
            NotifyOfPropertyChange(() => WebView);
        }
    }

    public string WebViewSource { get; set; } = "http://Google.com";

    private string _addressbar;

    public string Addressbar
    {
        get 
        { 
            return _addressbar; 
        }
        set 
        { 
            _addressbar = value;
            NotifyOfPropertyChange(() => Addressbar);
        }
    }


    public void ButtonGo()
    {
        if (WebView != null && WebView.CoreWebView2 != null)
        {
            WebView.CoreWebView2.Navigate("https://bing.com");
        }
    }

No matter what I try WebView keeps coming back null and I am not able to change the page.

2 Answers

A view model is not supposed to keep a reference to an element like WebView2. This is not MVVM and not how Caliburn.Micro works. A view model defines the source properties.

If you add a TextBlock property (you should not!) to the view model, it will also always be null just like your WebView2 property is, even if you add a TextBlock with a corresponding name in the XAML markup.

I am afraid this doesn't make much sense, both regarding MVVM in general and Caliburn.Micro in particular.

As aepot commented, removing the Webview property and notifying the change in the source resolved the issue. The code now looks like this for the view:

<Button x:Name="ButtonGo" 
        Content="Go"/>
<TextBox x:Name = "Addressbar"/>
<wv2:WebView2 x:Name = "WebView"
              Source="{Binding WebViewSource}"/>

And this for the ViewModel:

public string Addressbar
{
   get
   {
      return _addressbar;
   }
   set
   {
      _addressbar = value;
      NotifyOfPropertyChange(() => Addressbar);
   }
}

public void ButtonGo()
{
   WebViewSource = Addressbar;
   NotifyOfPropertyChange(() => WebViewSource);
}
Related