开发者

Displaying and editing a concatenated string enumerable in a bound WPF DataGrid

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.


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);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜