I have one way of getting this working but it seems a bit code smelly so better answers are welcomed. I created a static class holding an instance of the CompositionHost
. It has a method for resolving imports. The view's code behind calls the static class to create its view model.
public static class Container
{
public static CompositionHost Host { get; set; }
public static T Get<T>()
{
T obj = Host.GetExport<T>();
Host.SatisfyImports(obj);
return obj;
}
}
In the App
class:
public override async Task OnStartAsync(StartKind startKind, IActivatedEventArgs args)
{
var config = new ContainerConfiguration();
Container.Host = config.WithAssembly(GetType().GetTypeInfo().Assembly).CreateContainer();
await NavigationService.NavigateAsync(typeof(Views.MainPage));
}
In the view's code behind:
public sealed partial class MainPage : Page
{
private MainPageViewModel ViewModel { get; }
public MainPage()
{
InitializeComponent();
NavigationCacheMode = Windows.UI.Xaml.Navigation.NavigationCacheMode.Enabled;
ViewModel = Container.Get<MainPageViewModel>();
DataContext = ViewModel;
}
}