WPF textblock binding with List

后端 未结 4 1816
-上瘾入骨i
-上瘾入骨i 2020-11-29 08:48

does anyone know if there is a simple way to bind a textblock to a List. What I\'ve done so far is create a listview and bind it to the List and then I have a template withi

4条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-29 09:30

    Convert your List to a single string with "\r\n" as the delimiter in between. and bind that to the TextBlock. Make sure that the TextBlock is not restricted with its height , so that it can grow based on the number of lines. I would implement this as a Value Converter to XAML Binding which converts a List of strings to a single string with new line added in between

    
    

    The ListToStringConverter would look like this:

    [ValueConversion(typeof(List), typeof(string))]
    public class ListToStringConverter : IValueConverter
    {
    
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (targetType != typeof(string))
                throw new InvalidOperationException("The target must be a String");
    
            return String.Join(", ", ((List)value).ToArray());
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
    

提交回复
热议问题