0

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?

Angelo
  • 2,936
  • 5
  • 29
  • 44
  • 1
    You could explicitly resolve an instance of anything out a di container in the corner of your user control. Or you could use relativesource binding to get to a command in the datacontext of the window. – Andy Sep 10 '21 at 17:03
  • @Andy, Thanks! What do you mean by "in the corner of [my] user control"? – Angelo Sep 10 '21 at 18:45
  • 1
    Auto correct changed ctor to corner and i didn't notice. You'd usually resolve an instance of say a viewmodel out the di container and it'd automatically resolve any ctor parameters. You can, however, explicitly get an instance of a class out the di container anywhere you like in code. There's a potential downside to doing this for unit testing but you can have multiple ctor. – Andy Sep 11 '21 at 11:24
  • OK, that makes sense but AFAIK WPF UserControls must have a parameterless constructor. I think I have to figure out how to do it with relativesource binding. – Angelo Sep 11 '21 at 17:44
  • 1
    It depends on how and where the `UserControl` is instantiated. If you let the XAML processor take care of this, you will have to use property injection or some shared service to get a reference to the command. – mm8 Sep 13 '21 at 15:03
  • @mm8, thanks, it turns out that my problem was really about CommandBinding but I didn't see it because I went down too many rabbit holes. Will post an update if I get around to it. Basically, an approach similar to that described in http://www.nichesoftware.co.nz/2019/09/21/wordtutor-wpf-commands.html works for my issues. – Angelo Sep 13 '21 at 18:17

0 Answers0