Getting Unity to Resolve views in XAML

|▌冷眼眸甩不掉的悲伤 提交于 2019-11-30 22:05:49

The way to solve your problem is to make your window to have a ViewModel as well, with ViewModels of UserControls exposes as properties on it. Then in your XAML for a window you'd simply use Binding mechanism to bind UserControl's DataContexts to proper properties of your your main ViewModel. And since that main ViewModel is resolved from Unity container it would have all other ViewModel-s injected as needed.

This problem is normally solved using Regions and the RegionManager. In the main window ViewModel, a set of Regions is created and added to the RegionManager. Then ViewModels can be Resolved and added to the Region.Views collection.

In XAML, the Region is normally injected by having the ItemsSource property of an ItemsControl bound to the region property of the main ViewModel.

So, in the main screen ViewModel you would have something like this:

    public class TestScreenViewModel
{
    public const string MainRegionKey = "TestScreenViewModel.MainRegion";

    public TestScreenViewModel(IUnityContainer container, IRegionManager regionManager)
    {
        this.MainRegion = new Region();
        regionManager.Regions.Add(MainRegionKey, this.MainRegion);
    }

    public Region MainRegion { get; set; }
}

This would be Resolved normally in your IModule

        #region IModule Members

    public void Initialize()
    {
        RegisterViewsAndServices();

        var vm = Container.Resolve<SelectorViewModel>();
        var mainScreen = Container.Resolve<TestScreenViewModel>();
        mainScreen.MainRegion.Add(vm);

        var mainView = ContentManager.AddContentView("Test harness", mainScreen);
    }

    #endregion

And the XAML representation of your template looking something like

    <DataTemplate DataType="{x:Type TestModule:TestScreenViewModel}">
    <ScrollViewer ScrollViewer.VerticalScrollBarVisibility="Auto">
        <StackPanel>
            <ItemsControl ItemsSource="{Binding Path=MainRegion.Views}" />
        </StackPanel>
    </ScrollViewer>
</DataTemplate>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!