简体   繁体   中英

ViewModel calling a method of a user control (web browser)

I am trying to program in MVVM and I have the following use case:

  1. A TextBox 's text is bound to a property in the VM
  2. A Button is command bound to a relay command
  3. When the user presses the Button , the web browser's Navigate(url) method is called with the URL being the text in the TextBox

Above is the use case I want to create, but 1 and 2 is possible using the MVVM design pattern, but I could not find an adequate way to invoke the browser's Navigate() method. First of all, is it possible to call a method of a control from VM (please let me know if there is a way)? And in the above use case, what would be the appropriate way to structure the program if it is not possible?

Thanks

You could do the following:

  • Add a property MyUrl to your ViewModel
  • Bind MyUrl to your WebBrower's Source property

Make sure the property implements INotifyPropertyChanged . Then your Xaml:

<WebBrowser Source="{Binding MyUrl}" />

What if you REALLY wanted to call a UI method from the ViewModel?

If you ever do run into a situation where you absolutely need to call a method on a UI control for instance, you can hook up events on the ViewModel and then your UI registers to this event and does something UI specific...

VM code...

//... some VM logic
EpicNavigateEvent(url) // raise event, allowing UI to handle how

In your code-behind on your view (this is the part where some MVVM purests freak), you could register the event:

myVm.Navigate += doSomeNavigation;
...
public void doSomeNavigation(string url)
{
   // call Navigate
}

I've successfully used this approach for applications where we have a single ViewModel layer and multiple technologies hooked up the views (WinForms, WPF and Asp.Net).

If you're looking for something more elegant , have a look at the User Interaction Patterns on MSDN . The concept is the same though: Call something on the VM and the View is handles it appropriately.

Common scenarios for this type of approach is want to show a message to the user from the VM. Your VM should raise an event saying: ShowMyMessage("You're awesome") , then your UI is notified and handles it: MessageBox.Show(msg) or whatever.

As long as you stick to there rules you should be golden:

  • ViewModels should NOT be concerned about UI code
  • Views must ONLY handle the presentation of the data provided by your ViewModels.
  • Don't overcomplicate it. KISS ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM