In order to support initialization of a list from a string that contains comma-separated elements, like
MyList="one, two, three"
you would register a custom TypeConverter
.
Note that the code below uses IList<string>
as property type, which provides greater flexibility in the types assignable to the property, and thus simpler implementation of the TypeConverter (which returns a string[]
).
public partial class MyControl : UserControl
{
public static readonly DependencyProperty MyListProperty =
DependencyProperty.Register(
nameof(MyList),
typeof(IList<string>),
typeof(MyControl));
[TypeConverter(typeof(StringListConverter))]
public IList<string> MyList
{
get { return (IList<string>)GetValue(MyListProperty); }
set { SetValue(MyListProperty, value); }
}
}
public class StringListConverter : TypeConverter
{
public override bool CanConvertFrom(
ITypeDescriptorContext context, Type sourceType)
{
return sourceType == typeof(string);
}
public override object ConvertFrom(
ITypeDescriptorContext context, CultureInfo culture, object value)
{
return ((string)value).Split(
new char[] { ',', ' ' },
StringSplitOptions.RemoveEmptyEntries);
}
}