In an MVVM application I am currently creating, I had the need to embed the WPF WebBrowser control and quickly discovered that the Source Property is not a dependancy object, and so cannot be bound.

I quickly search around on and found a neat solution in c#;

The VB Version of which is;

Namespace Helpers

''' Allows for the Source Property of the WebBrowser to be Bindable to the DataContext
Public Class WebBrowserUtility

Public Shared ReadOnly BindableSourceProperty As DependencyProperty = DependencyProperty.RegisterAttached("BindableSource", GetType(String), GetType(WebBrowserUtility), New UIPropertyMetadata(Nothing, AddressOf BindableSourcePropertyChanged))

Public Shared Function GetBindableSource(obj As DependencyObject) As String
Return DirectCast(obj.GetValue(BindableSourceProperty), String)
End Function

Public Shared Sub SetBindableSource(obj As DependencyObject, value As String)
obj.SetValue(BindableSourceProperty, value)
End Sub

Public Shared Sub BindableSourcePropertyChanged(o As DependencyObject, e As DependencyPropertyChangedEventArgs)
Dim browser As WebBrowser = TryCast(o, WebBrowser)
If browser IsNot Nothing Then
Dim uri As String = TryCast(e.NewValue, String)
browser.Source = If(uri IsNot Nothing, New Uri(uri), Nothing)
End If
End Sub

End Class

End Namespace

You then use your new Bindable Property in the XAML as;

Then simply creating a Property in the DataContext, and setting the source like;

KioskWebAddress = "c:/HTML/index.html"

By |2017-07-24T08:33:18+01:00May 21st, 2013|.Net Framework, Binding, HTML, MVVM, Tips,, Visual Studio, WPF|0 Comments

About the Author:

Leave A Comment