Angelo
Angelo

Reputation: 3115

WPF .net 5 application with DI: accessing services from RoutedCommand in a UserControl

I've got a UserControl in a WPF application which has a RoutedCommand. The RoutedCommand needs to access a service that I've registered in the DI container.

The problem is that I can't figure out how to get a reference to the service so the RoutedCommand can use it.

Normally, I would just inject whatever service I need into the constructor of the ViewModel and, of course, the ViewModel would also be registered in the DI container.

In this case, however, the UserControl's DataContext is just itself (it has no separate ViewModel). I don't even explicitly instantiate the UserControl because that's handled by WPF infrastructure through a parameterless constructor. The UserControl is just items for a WPF ListBox.

I tried making a dependency property in the UserControl to hold the service, but that doesn't seem to work. Maybe I did it wrong, but I don't even know if that's the right path forward.

FWIW, I am not using any library/framework like PRISM. Is there a way to do this that I am just not seeing?

Upvotes: 0

Views: 121

Answers (0)

Related Questions