How to inject a Converter in XAML

后端 未结 2 908
天涯浪人
天涯浪人 2021-02-04 15:47

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

相关标签:
2条回答
  • 2021-02-04 16:12

    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.

    0 讨论(0)
  • 2021-02-04 16:20

    An alternative approach is, to resolve the dependency via MarkupExtension and set it to the converter's property in XAML.

    See the following answer for details:

    https://stackoverflow.com/a/41611854/2115905

    0 讨论(0)
提交回复
热议问题