Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do you access the MainViewModel in ViewModelLocator from code behind?
    text
    copied!<p>Building a WP7 app using MVVM light for my view models. I'm using the ViewModelLocator that gets added when you add the library through NuGet. Works great but now I need to get access to a ViewModel from code.</p> <p>In my code the user clicks a button and I need to search the MainViewModel (which contains several view models) and find one based on the criteria the user entered.</p> <p>Normally I would just response to the Click event of the button but I don't have an instance variable of the ViewModelLocator class to get a hold of the MainViewModel to perform the search. With the default template (non-MVVMLight) for Windows Phone 7, the App class has a static variable to the main view model so you can access it anytime with App.ViewModel.</p> <p>There's some talk from twitter about using commands which would be good, but at some point I have to perform a code search across multiple vms to get the results I need. Probably need to inject a ISearchViewModel service into the View or something to make this work.</p> <p>Here's the implementation of ViewModelLocator that is provided:</p> <pre><code>public class ViewModelLocator { private static MainViewModel _main; public ViewModelLocator() { _main = new MainViewModel(); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "This non-static member is needed for data binding purposes.")] public MainViewModel Main { get { return _main; } } } </code></pre> <p>So from the code behind of another view, how do you get access to Main (MainViewModel contains all the lists of data and has a search method I call)? Or Should you?</p> <p>Just wondering how people are solving this type of problem?</p> <p>Thanks.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload