字符串数组在XAML中以逗号分隔的字符串

bar*_*ian 6 .net wpf xaml

如何在xaml中设置string []属性的值?

我控制下一个属性:string [] PropName

我想以下一种方式设置此属性的值:

<ns:SomeControl PropName="Val1,Val2" />
Run Code Online (Sandbox Code Playgroud)

svi*_*ick 9

您可以使用<x:Array>标记扩展,但它的语法相当冗长.

另一种选择是创建自己的TypeConverter,可以从逗号分隔列表转换为数组:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您要转换的类型是您的类型,则可以将该[TypeConverter]属性应用于该类型.但既然你想转换成string[],你就不能这样做.因此,您必须将该属性应用于要使用此转换器的所有属性:

[TypeConverter(typeof(ArrayTypeConverter))]
public string[] PropName { get; set; }
Run Code Online (Sandbox Code Playgroud)