Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String array as comma separated string in XAML

Tags:

.net

wpf

xaml

How I can set value of string[] property in xaml?

I hava control with next property: string[] PropName

I want to set value of this property in next way:

<ns:SomeControl PropName="Val1,Val2" />
like image 289
barbarian Avatar asked Dec 07 '11 10:12

barbarian


1 Answers

You can use the <x:Array> markup extension, but its syntax is quite verbose.

Another option is to create your own TypeConverter that can convert from the comma-separated list to an array:

class ArrayTypeConverter : TypeConverter
{
    public override object ConvertFrom(
        ITypeDescriptorContext context, CultureInfo culture, object value)
    {
        string list = value as string;
        if (list != null)
            return list.Split(',');

        return base.ConvertFrom(context, culture, value);
    }

    public override bool CanConvertFrom(
        ITypeDescriptorContext context, Type sourceType)
    {
        if (sourceType == typeof(string))
            return true;

        return base.CanConvertFrom(context, sourceType);
    }
}

If the type you were converting to was your type, you could then apply the [TypeConverter] attribute to that type. But since you want to convert to string[], you can't do that. So you have to apply that attribute to all properties where you want to use this converter:

[TypeConverter(typeof(ArrayTypeConverter))]
public string[] PropName { get; set; }
like image 170
svick Avatar answered Nov 15 '22 17:11

svick