开发者

XAML Automatic Type Conversion

开发者 https://www.devze.com 2023-03-04 05:05 出处:网络
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

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开发者_StackOverflow社区.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


The magic you are refering to is due to the framework's use of the TypeConverter attribute.

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.

http://blogs.windowsclient.net/rob_relyea/archive/2008/04/10/strings-to-things-or-how-xaml-interprets-attribute-values.aspx


Maybe you can try a BrushConverter.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号