1

I want to join a list and bind them within a TextBlock in a GridView (or ListView) block.

Let me draw a picture to explain the scenario.

C#

I have a list of StudentInfo which contains Name (string), ID (int) and Courses (List<string)

XAML

<ListView.ItemTemplate>
    <DataTemplate x:DataType="data:StudentInfo">
        <StackPanel>
            <TextBlock Text="{x:Bind StudentName}" Margin="1"/>
            <TextBlock Text="{x:Bind ID}" Margin="1"/>
            <!--In the following textblock, I want to show something like this
                "Taken Courses Are - PHY, CHM, MAT"-->
            <TextBlock Text="{x:Bind Courses}" Margin="1"/>
        </StackPanel>
    </DataTemplate>
</ListView.ItemTemplate>

In the last TextBlock I want to join all the courses a student have taken and show them with a hard coaded text -

"Taken Courses Are - ".

How can I do that?

Mahmudul Hasan
  • 798
  • 11
  • 35

2 Answers2

3

you can simply use a IValueConverter to Bind list

<TextBlock Text="{x:Bind Courses,Converter={StaticResource ListToStringConverter}}" Margin="1"/>

Here the Converter

public class ListToStringConverter : IValueConverter
{

    public object Convert(object value, Type targetType,
        object parameter, string language)
    {    
        return String.Join(", ", ((List<string>)value).ToArray());
    }

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

Edit

Add ListToStringConverter to your resources

<Page.Resources>
            <local:ListToStringConverter x:Name="ListToStringConverter" ></local:ListToStringConverter>
</Page.Resources>
Vignesh
  • 1,824
  • 2
  • 10
  • 27
1

Write a converter class to covert your list to a comma separated string.

XAML code


    <TextBlock Text="{Binding Path=Courses,Converter={StaticResource CourseToStringConverter}}" Margin="1"/>

CourseToStringConverter

[ValueConversion(typeof(List<string>), typeof(string))]
public class CourseToStringConverter: 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 "Taken Courses Are - " + String.Join(", ", ((List<string>)value).ToArray());
    }

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