Using Unity in WPF

北城以北 提交于 2019-12-04 16:12:53

I believe bringing together Controls and IoC is pain in the ... in the code at least. Probably somebody will argue but IMO the best practice to avoid this pain is MVVM. You will have viewModels which you can freely construct using Unity and inject everything you need into them. You will have views with bindings to viewModels with no reason to know anything abound inversion of control.

UPDATE: Based on comment:

App.xaml.cs:

    private void HandleStartup(object sender, StartupEventArgs e)
    {
        var container = CreateContainer(); // create IoC container
       var mainViewModel = container.Resolve<MainViewModel>();
        var shell = new Shell { DataContext = mainViewModel }; // main View
        MainWindow = shell;
        shell.Show();
    }

Shell XAML example:

<UserControl>
     <StackPanel>
          <ContentPresenter Content="{Binding ViewModel1}" />
          <ContentPresenter Content="{Binding ViewModel2}" />
          <ContentPresenter Content="{Binding ViewModel3}" />
     </StackPanel>
</UserControl>

MainViewModel:

public class MainViewModel
{
     public ViewModel1 ViewModel1 { get; private set; }
     public ViewModel2 ViewModel2 { get; private set; }
     public ViewModel3 ViewModel3 { get; private set; }

     // this will be handled by IoC container
     public MainViewModel(ViewModel1 viewModel1, ViewModel2 viewModel2, ViewModel3 viewModel3)
    {
        ViewModel1 = viewModel1;
        ViewModel2 = viewModel2;
        ViewModel3 = viewModel3;
    }

In this way your views will be unaware of IoC and everything you want in viewModels will be successfully injected.

UPDATE2 DataTemplating which brings Views and ViewModels together:

App.xaml

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