views:

18

answers:

1

I'm using a WPF DataGrid with binding in order to display and edit various properties of a class. Many of these properties are IEnumerable<string>. I would like to display these concatenated, with each item of the enumerable separated by a newline character. The value must also be editable - after an edit, the concatenated string should be split on each newline and assigned back into the bound property.

For example:

The enumerable {"a","b","c"}

becomes:

"a    
b    
c"

It is then edited in the grid to:

"alpha    
b    
cat"

And the bound property is updated to: {"alpha","b","cat"}

Is there a way of overloading one of the DataGridColumn classes to do this?

EDIT: Thanks to Quartermeister I got this working. I'm using autogenerated columns, so in my AutoGeneratingColumn event I did the following:

                if (e.PropertyType == typeof(IEnumerable<string>)) {
                DataGridTextColumn dgtc = e.Column as DataGridTextColumn;
                JoinStringEnumerableConverter con = new JoinStringEnumerableConverter();
                (dgtc.Binding as Binding).Converter = con; 
            }

Where e is the eventargs. This added the converter to the binding, and it seems to work fantastically. Thanks again.

+1  A: 

You could create a custom IValueConverter and use it on the binding. Something like this:

public class JoinConverter
    : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var enumerable = value as IEnumerable<string>;
        if (enumerable == null)
        {
            return DependencyProperty.UnsetValue;
        }
        else
        {
            return string.Join(Environment.NewLine, enumerable.ToArray());
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return value.ToString().Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
    }
}
Quartermeister
This was perfect, thanks. See my question for the implementation.
Daniel I-S