问题描述
我注意到可以从值转换器返回类似"Visible","Collapsed","Images/xyz.png"或#FFB3D1"的字符串,而绑定的魔力设法弄清楚了它.隐藏/显示UI元素,找到xyz.png图像或将颜色涂成粉红色...
I've noticed it's possible to return a string like "Visible", "Collapsed", "Images/xyz.png" or "#FFB3D1" from a value converter and the magic of bindings manages to figure it out. Hide/Show the UI Element, find the xyz.png image or colour something pink...
我已经很长时间了,现在它不能与我的最新代码一起使用,所以我的问题是如何手动调用此功能?
I've taken this for granted for a long time, it now it doesn't work with my latest code, So my Question is how can I manually call this functionality?
说明:
我已经通过创建自定义MarkupExtension进行了扩展,该MarkupExtension附加了一个MultiConverter并将其附加到MultiBinding并返回初始化的绑定.但是,当此多转换器返回#FFB3D1"或"Red"之类的字符串时,似乎什么也没发生.
I've scaled up by creating a custom MarkupExtension, which attaches a MultiConverter attaches it to a MultiBinding and returns the initialised binding. However when this multi converter returns strings like "#FFB3D1" or "Red", nothing seems to happen.
// PseudoCode from my MarkupExtension, setting up & returning the binding/multi-converter
public override object ProvideValue( IServiceProvider serviceProvider )
{
MultiBinding outputBinding = new MultiBinding();
foreach ( Binding b in bindings )
{
outputBinding.Bindings.Add( b );
}
outputBinding.Converter = converter;
return outputBinding.ProvideValue( serviceProvider );
}
我猜想是因为我正在用代码创建Multibinding + Converter,所以它跳过了 Binding.Magic
名称空间中的某个地方.
I presume that because I'm creating the Multibinding + Converter in code, it's skipping a step somewhere in the Binding.Magic
namespace.
解决方案:
public override object ProvideValue( IServiceProvider serviceProvider )
{
// get targets
IProvideValueTarget serv = (IProvideValueTarget)serviceProvider.GetService( typeof( IProvideValueTarget ) );
// get Type Converter
object[] typeConverterAttributes = ( (DependencyProperty)serv.TargetProperty ).PropertyType.GetCustomAttributes( typeof( TypeConverterAttribute ), true );
TypeConverter typeConverter = null;
if ( typeConverterAttributes.Length > 0 )
{
TypeConverterAttribute attr = (TypeConverterAttribute)typeConverterAttributes[0];
typeConverter = (TypeConverter)Activator.CreateInstance( Type.GetType( attr.ConverterTypeName ), false );
}
这只是手动应用类型转换器的一种情况
It is then simply a case of applying the Type Converter manually
推荐答案
您所指的魔术是由于框架使用了 TypeConverter
属性.
The magic you are refering to is due to the framework's use of the TypeConverter
attribute.
如果这是您要绑定的自己的属性,也许您应该定义一个新的TypeConverter并用TypeConverter属性装饰该属性.
If this is your own property that you are binding to, maybe you should define a new TypeConverter and decorate the property with the TypeConverter attribute.
这篇关于XAML自动类型转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!