开发者

Dependency Injection in XAML (WPF)

开发者_StackOverflow

I am creating a new WPF project and we use Microsoft Unity as DI.

I am having a user control which is calling a 3rd party service.

So now how to inject dependency from the main window XAML for the usercontrol.


You can use the service locator pattern. I use it with Unity as a DI.

internal class ServiceLocator
{
    [...]
    public MainViewModel Main { get { return container.Resolve<MainViewModel>(); } }
}

You can intantiate your class the way you want (DI or not, the class initializes the DI etc...).

In your App.xaml

<Application.Resources>
        <vm:ServiceLocator x:Key="Locator"/>
    </Application.Resources>

And now, you can set your datacontext

DataContext="{Binding Main, Source={StaticResource Locator}}"

Edit:

I found another way of doing it (among other): Take a look at this article. In the command, you can resolve your viewmodel as you like.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜