Introduction
The WPF WebBrowser
control is extremely sad in the capabilities it provides, and even in supporting the MVVM pattern. I created a control to enhance the capabilities of the WebBrower
to support easy interface using ICommand
for forward and back buttons, and the MVVM design pattern. Since Microsoft made things even sillier because the WebBrowser
is Sealed, I had to inherit from the ContentControl
and this ContentControl
only contains a WebBrowser control.
The following are the capabilities this control has:
NavigateString
(string
) DependencyProperty
which will execute the WebBrowser
Navigate
method.
HeaderString
(string
) DependencyProperty
which will set the cookies for the brower. The string
contains the cookie items separated by a ";" with each cooking being the key, an equal sign ("=") and then the value.
- An
IsSuccessful
DependencyProperty
that is set to null
when navigation is started, and then changes to true
if it appears that the navigation was successful, and false
is not. The way it is determined that the navigation was not successful is if the Document
Url
property starts with "res://ieframe.dll".
- A
Body
DependencyProperty
that will allow the content of the WebBrowser
to be defined by a string
containing HTML.
- A
BrowseForward
and BrowseBack
ICommand
that allows a Button
to be bound to the WebBrowserControl
for navigation forward and back.
- The silencing of error messages by the browser that are probably due to javascript errors (I was having a lot of trouble with this on some sites I browsed to).
- A way to discover and update the Internet Explorer browser version used by the control.
- Ability to disable/enable
WebBrowser
ContextMenu
(disabled by default)
Using the code
This is an example of using the control using the MVVM design pattern
<local:WebBrowserControl x:Name="Browser"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
HeaderString="{Binding WebCookies}"
IsSuccessful="{Binding IsSuccessful, Mode=OneWayToSource}"
NavigateString="{Binding WebUri}" />
Note
The sample uses the URI "http://request.urih.com/" because this will show the cookies.
The sample above has red boxes to show where the token information can be found.
Conclusion
This control could be significantly enhanced, but includes a lot of snippets that should be quite useful to anyone trying to implement a WebBrowser
in WPF, and also is a good template for implementing enhancements. If anyone has any thoughts on how this can be improved, I am definitely interested.
History
- 2016-11-28: Initial Version
- 2017-01-20: Added abiltiy to remove
WebBrowser
ContextMenu
(thanks to code provided by Simon Mourier