Saturday, December 6, 2014

InjectionMap.Wpf: Extension for InjectionMap

InjectionMap.Wpf is a extension to InjectionMap that allows to define the ViewModel in the xaml of the View. InjectionMap will resolve the ViewModel and bind it to the DataContext of the View. All parameters of the constructor can be resolved using ConstructorInjection.

Create a ViewModel. A class that will be added to the DataContext
namespace ViewModels
{
 public class ViewModel : INotifyPropertyChanged
 {
  public ViewModel(ISettings settings)
  {
    ...
  }
 }
}

Map the dependencies

using(var mapper = new InjectionMapper())
{
      mapper.Map<ISettings, Settings>();
}

Bind the ViewModel to the View

<Window x:Class="MainWindow"
 xmlns:wf="http://schemas.wickedflame.ch/2013/xaml/presentation"
        xmlns:vm="clr-namespace:ViewModels"
        wf:InjectionResolver.Resolve="{x:Type vm:ViewModel}">
 <!-- Optional Namespace for InjectionMap.Wpf: xmlns:wf="clr-namespace:InjectionMap;assembly=personalplaner.common" -->
...
</Window>
The ViewModel will be resolved and bound to the DataContext of the UserControl/Window.