I'm trying to add a DependencyProperty to my WebBrowser control in my WP8 app so that I can bind the source to a property within my ViewModel.
I found this thread on StackOverflow databind the Source property of the WebBrowser in WPF
Since this applied to WPF, I've had to make a few changes to behaviour code (nothing major):
public class WebBrowserBehaviors : Behavior<WebBrowser>
{
protected override void OnAttached()
{
base.OnAttached();
}
protected override void OnDetaching()
{
base.OnDetaching();
}
public static readonly DependencyProperty BindableSourceProperty= DependencyProperty.Register(
"BindableSource",
typeof(bool),
typeof(WebBrowserBehaviors),
new PropertyMetadata(BindableSourcePropertyChanged)
);
public static void SetBindableSource(DependencyObject obj, string value)
{
obj.SetValue(BindableSourceProperty, value);
}
public static string GetBindableSource(DependencyObject obj)
{
return (string)obj.GetValue(BindableSourceProperty);
}
public static void BindableSourcePropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
WebBrowser browser = o as WebBrowser;
if (browser == null) return;
Uri uri = null;
if (e.NewValue is string)
{
var uriString = e.NewValue as string;
uri = string.IsNullOrWhiteSpace(uriString) ? null : new Uri(uriString);
}
else if (e.NewValue is Uri)
{
uri = e.NewValue as Uri;
}
browser.Source = uri;
}
}
The thread also provide a XAML sample:
<WebBrowser ns:WebBrowserUtility.BindableSource="{Binding WebAddress}"
ScrollViewer.HorizontalScrollBarVisibility="Disabled"
ScrollViewer.VerticalScrollBarVisibility="Disabled"
Width="300"
Height="200" />
But I'm having 2 problems:
Problem 1:
I declared my namespace as follows:
xmlns:behaviors="clr-namespace:MyApp.Behaviors"
My WebBrowser control is defined as follows and I've removed my
Source={Binding CurrentUri}
and replaced it bybehaviors:WebBrowserBehaviors.BindableSource
.`<Grid Grid.Row="0" > <phone:WebBrowser x:Name="webBrowser" behaviors:WebBrowserBehaviors.BindableSource="{Binding ...}" IsScriptEnabled="True" NavigationFailed="webBrowser_NavigationFailed" Navigating="webBrowser_Navigating" LoadCompleted="webBrowser_LoadCompleted" Navigated="webBrowser_Navigated" IsEnabled="{Binding IsLoading.IsFalse}"> </phone:WebBrowser> </Grid>`
And while intellisense detects
behaviours
,WebBrowserBehaviors
, andBindableSource
it displays the following error message:Error 1 DependencyProperty MyApp.Behaviors.WebBrowserBehaviors. BindableSource cannot be set on an object of type Microsoft.Phone.Controls.WebBrowser.
Problem 2:
Originally I had
<WebBrowser Source={Binding CurrentUri}>
but when I try to use
behaviors:WebBrowserBehaviors.BindableSource="{Binding ...}"
intellisense doesn't show me any of my ViewModels property which are binded to my layoutRoot.
I don't know if it's related to problem 1, but I thought I'd better mention it.
Can anyone help?
Thanks.