Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inject a Converter in XAML

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.

like image 658
PandaWood Avatar asked May 23 '09 04:05

PandaWood


1 Answers

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.

like image 109
Kent Boogaart Avatar answered Oct 20 '22 21:10

Kent Boogaart