如何在XAML中注入转换器 [英] How to inject a Converter in XAML

查看:83
本文介绍了如何在XAML中注入转换器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个IValueConverter实现的类,我需要使用我的DI容器(Ninject)注入它。

I have an IValueConverter implemented class and I need it to be injected using my DI container (Ninject).

问题是,在XAML中,没有立即显而易见的问题

The problem is, in XAML, there's no immediately obvious way to get control over the instantiation of the Converter object.

因此,我的XAML包含以下内容:

So my XAML contains a line something like this:

Source = {Binding Path = CurrentMessage,Converter = {StaticResource ImagePathConverter}}

Source="{Binding Path=CurrentMessage, Converter={StaticResource ImagePathConverter}}"

其中,将为我创建 ImagePathConverter

我想我可以创建一个服务定位器静态类,并调用它来解决我的依赖性并将StaticResource更改为属性 MyServiceLocator.TheImageConverter,但这使我想呕吐。

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.

另外,非常重要的是,假设XAML 没有代码隐藏-并且我不能使用一个。我正在创建皮肤,并且不需要后面的代码。因此,我无法在类构造函数中设置类变量并引用它。

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.

推荐答案

一种常见的处理方法是让您的转换器也成为 MarkupExtension 。即:

A common way to handle this is for your converter to also be a MarkupExtension. That is:

public class MyConverter : MarkupExtension, IValueConverter

您的 ProvideValue()方法可以返回转换器的实例,从而允许您像这样使用它:

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}}"

这与DI无关,但是确实满足了消除后面代码的要求。我真的看不到在您的DI容器中注册转换器的意义。

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.

这篇关于如何在XAML中注入转换器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆