I have an IValueConverter implemented class and I need it to be injected using my DI container (Ninject).
The problem is, in XAML, there's no immediately obvious way to get control over the instantiation of the Converter object.
So my XAML contains a line something like this:
Source="{Binding Path=CurrentMessage, Converter={StaticResource ImagePathConverter}}"
Where, the ImagePathConverter will be created for me.
I suppose I could create a "service locator" static class and call it to resolve my dependency and change the StaticResource to a property "MyServiceLocator.TheImageConverter", but that makes me want to vomit.
I am hoping this question can be answered with a few snippets of code that specifically target the code supplied - and perhaps a supporting link to an example. Not simply a recommendation to take a look somewhere.
Also, very importantly, assume that the XAML does not have a code-behind - and that I cannot use one. I'm creating a skin and do not want a code behind. So I cannot set a class variable in the class constructor and reference it. Maybe that's unreasonable, I'm not sure yet.
A common way to handle this is for your converter to also be a MarkupExtension
. That is:
public class MyConverter : MarkupExtension, IValueConverter
Your ProvideValue()
method can return an instance of your converter, thus allowing you to use it like this:
Source="{Binding CurrentMessage, Converter={local:MyConverter SomeParameterToConverter}}"
This isn't really anything to do with DI, but it does address your requirement to eliminate the code behind. I don't really see the point of having converters registered with your DI container.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With