'XAML Automatic Type Conversion
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?
Explanation:
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 );
}
I presume that because I'm creating the Multibinding + Converter in code, it's skipping a step somewhere in the Binding.Magic namespace.
Solution:
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
Solution 1:[1]
Maybe you can try a BrushConverter.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ben |
