Note that there are some explanatory texts on larger screens.

plurals
  1. PODependency Injection with MVVM and Child Windows
    primarykey
    data
    text
    <p>I am using MVVM Light and I'm currently using SimpleIoC that comes with the package. I'm getting a bit stuck with the dependency injection. I have a bunch of services that I want to use in my view models, however most windows are a List-Edit paradigm, i.e. one screen lists all of type <code>Person</code> and then you can Add or Edit a <code>Person</code> via a new screen.</p> <p>When I was doing all code in the code behind my code for adding and editing a record was as follows:</p> <p><strong>View</strong></p> <pre><code>private void btnEdit_Click(object sender, RoutedEventArgs e) { _viewModel.Edit(); } private void btnAdd_Click(object sender, RoutedEventArgs e) { _viewModel.Add(); } </code></pre> <p><strong>View Model</strong></p> <pre><code>public void Add() { var f = new TypeDetails(); f.Show(); } public void Edit() { if (SelectedItem == null) return; var f = new TypeDetails(SelectedItem.Id); f.Show(); } </code></pre> <p>The constructor of <code>TypeDetails</code> is as follows:</p> <pre><code>public TypeDetails(int id = 0) { InitializeComponent(); _viewModel = new TypeDetailsViewModel(id); DataContext = _viewModel; } </code></pre> <p>What would the best be to implement this type functionality with MVVM Light? I have been using the <code>ViewModelLocator</code> class for the List screens, however I cannot see a way to do this using the SimpleIoC. My way round so far has been to keep the constructor the same, which works fine until I need to inject dependencies into the <code>TypeDetailsViewModel</code> such as a service. With a service the constructor of <code>TypeDetailsViewModel</code> would be:</p> <pre><code>public TypeDetailsViewModel(ISomeService someService, int id = 0) { ... } </code></pre> <p>But that means in my view constructor I have to build these dependencies one at a time and manually inject them...</p> <pre><code>public TypeDetails(int id = 0) { InitializeComponent(); _viewModel = new TypeDetailsViewModel(SimpleIoC.Current.GetInstance&lt;ISomeService&gt;(),id); DataContext = _viewModel; } </code></pre> <p>Is there a better way to do this? </p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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