views:

978

answers:

3

Hi All

Im writing an app in WPF using MVVM pattern, where Im restricted to binding to properties and commands exclusivley

However, I want to use the WebBrowser control which can only take an html string for content as a parameter to a mthod, and not a property.

I was going to create a new control derived from Webbrowser that has the required property, but the control class is sealed. I tried creating a wrapper control, but I had all sorts of problems with dependency properties that seemed to be more trouble solving than I could be bothered with.

Is there any way I can push a parameter(string) into a method with MVVM without resorting to code in the code-behind files (which is a big no-no).

Thanks

Dean

+2  A: 

I'm not entirely sure I understand the question (you want to call a method on the WebBrowser, but need an html string to do so?).

MVVM isn't about avoiding code-behind like the plague as much as it's about relegating code-behind files to strictly UI tasks.

If you set up your UI to include a typical Address Bar + Go button, you'll want to use the Buttons' Click handler to pass the string to the browser. Alternatively, the string could be a property of the ViewModel and you could collect it easily by binding it to the Tag property of the WebBrowser.

Your UI will appear roughly like this:

<TextBox x:Name="addressBar" /> <!-- If you use the address bar -->
<Button Content="Go" Click="NavigateButton_Click" />
<WebBrowser x:Name="browser" Tag="{Binding URL}" />  <!-- If you bind to a VM property -->

Your code-behind could look like this:

void NavigateButton_Click(object sender, RoutedEventArgs e)
{
   browser.Navigate(new Uri(addressBar.Text)); // Address Bar
   browser.Navigate(new Uri(browser.Tag.ToString()); // Tag Binding
}
KP Adrian
+2  A: 

I used the solution found here

http://stackoverflow.com/questions/263551/databind-the-source-property-of-the-webbrowser-in-wpf

HTH

Yep, an attached property is the easies way to make binding possible on a non-dependency property
Thomas Levesque
+2  A: 

Why is any code in the code-behind files a no go? I believe this is one of the most seen misunderstandings in the MVVM community.

MVVM is not a pattern to eliminate the code behind. It is to separate the view part (appearance, animations, etc.) from the logic part (workflow). Furthermore, you are able to unit test the logic part.

I know enough scenarios where you have to write code behind because data binding is not a solution to everything. Sample applications that use code behind and still fulfill the MVVM separation can be found here:

WPF Application Framework (WAF)

jbe