2

I have a collection of items and want to show it in a ListView as a List of comma separated values. How can I show a comma in between the values?

So far I've created a ItemsPanelTemplate with a <VirtualizingStackPanel IsItemsHost="True" Orientation="Horizontal"/> as only child.

Obviously creating a DataTemplate which includes the comma would result in a tailing comma, where I don't want one.

H.B.
  • 166,899
  • 29
  • 327
  • 400
Mene
  • 3,739
  • 21
  • 40
  • How about `string.Join()` in your ViewModel? – H H Aug 05 '12 at 16:32
  • Yes, if the items of the list were strings that would be an easy solution, however I want a more general solution. The comma-separation was just an illustration of the problem. And while I actually want a space-separation and the elements themselves are strings, I still don't want to join them, because they should have different colors and different hover-effects etc. – Mene Aug 05 '12 at 16:56
  • 2
    Please see my answer [here](http://stackoverflow.com/a/3351693/5380). – Kent Boogaart Aug 05 '12 at 18:06

1 Answers1

0

Use this converter...

public class StringListConverter : IValueConverter { public StringListConverter() { Separator = CultureInfo.CurrentCulture.TextInfo.ListSeparator + " "; }

    public string Separator { get; set; }



    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        string result = "";
        if (value is IList<string> && targetType.IsAssignableFrom(typeof(string)))
        {
            result = string.Join(Separator, (value as IList<string>).ToArray());
        }
        return result;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

In XAML in the resources:

<rw:StringListConverter x:Key="StringListConverter"/>

then

<TextBlock Text="{Binding ItemList, Converter={StaticResource StringListConverter}}"/>
Joe Sonderegger
  • 784
  • 5
  • 15