0

I have been working on a WPF UI Control.

I have defined a dependency property which is a List of strings.

This binds with a list property on a view model as expected.

What I would like to do is have the option to define the list in the XAML rather than bind to a list on the view model.

<local:MyControl MyList = "one,two,three">

The MyList Property on my control.

public static readonly DependencyProperty MyListProperty =
            DependencyProperty.Register("MyList", typeof(List<string>), typeof(MyControl));
Lance
  • 251
  • 5
  • 13

1 Answers1

1

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);
    }
}
Clemens
  • 123,504
  • 12
  • 155
  • 268
  • I was trying to get the System.Configuration.CommaDelimitedStringCollectionConverter to work to no avail, @Clemens answer worked perfectly - thank you. – Lance Nov 06 '19 at 20:33
  • Which won't work because `CommaDelimitedStringCollection` does not implement `IList`. – Clemens Nov 06 '19 at 20:36