Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an MVVM-friendly way to use the WebBrowser control in WPF?

Thanks to this question (click me!), I have the Source property of my WebBrowser binding correctly to my ViewModel.

Now I'd like to achieve two more goals:

  1. Get the IsEnabled property of my Back and Forward buttons to correctly bind to the CanGoBack and CanGoForward properties of the WebBrowser.
  2. Figure out how to call the GoForward() and GoBack() methods without resorting to the code-behind and without the ViewModel having to know about the WebBrowser.

I have the following (non-working) XAML markup at the moment:

<WebBrowser
    x:Name="_instructionsWebBrowser"
    x:FieldModifier="private"
    clwm:WebBrowserUtility.AttachedSource="{Binding InstructionsSource}" />

<Button
    Style="{StaticResource Button_Style}"
    Grid.Column="2"
    IsEnabled="{Binding ElementName=_instructionsWebBrowser, Path=CanGoBack}"
    Command="{Binding GoBackCommand}"
    Content="&lt; Back" />

<Button
    Style="{StaticResource Button_Style}"
    Grid.Column="4"
    IsEnabled="{Binding ElementName=_instructionsWebBrowser, Path=CanGoForward}"
    Command="{Binding GoForwardCommand}"
    Content="Forward &gt;" />

I'm pretty sure the problem is that CanGoBack and CanGoForward are not dependency properties (and don't implement INotifyChanged), but I'm not quite sure how to get around that.

Questions:

  1. Is there any way to hook up attached properties (as I did with Source) or something similar to get the CanGoBack and CanGoForward bindings to work?

  2. How do write the GoBackCommand and GoForwardCommand so they are independent of the code-behind and ViewModel and can be declared in markup?

like image 306
devuxer Avatar asked Sep 05 '09 20:09

devuxer


1 Answers

For anyone who comes across this question and wants a complete solution, here it is. It combines all of the suggestions made in this thread and the linked threads (and others those link to).

XAML: http://pastebin.com/aED9pvW8

C# class: http://pastebin.com/n6cW9ZBB

Example XAML usage: http://pastebin.com/JpuNrFq8

Note: The example assumes your view binds to a ViewModel that provides the source URL to the browser. A very rudimentary navigation bar with back, forward, and refresh buttons and address bar is provided just for demonstration.

Enjoy. I have set the expiration on those pastebin's to never, so they should be available for as long as pastebin exists.

like image 63
2 revs Avatar answered Sep 30 '22 18:09

2 revs