Home » c# » c# – Nested List<List<string>> XAML output to ListView

c# – Nested List<List<string>> XAML output to ListView

Posted by: admin February 21, 2020 Leave a comment

Questions:

I’m hoping someone has had a similar issue to me and can help me out!

I am trying to bind an ObservableCollection<List<string>> to a ListView but I’m having issues formatting the output.

Here is the nested structure:

C#

 //Setting variables
 private ObservableCollection<List<string>> _results;
 public ObservableCollection<List<string>> Results
 {
      get => _results;
      set { _results = value; OnPropertyChanged(nameof(Results)); }
 }

 //Initialise variables
 private async Task<bool> runAsync() {
      List<List<string>> targets = new List<List<string>>();
      targets = await Task.FromResult(dataConverter.getFromFile());

      Results = new ObservableCollection<List<string>>(targets);
      foreach (var target in targets)
       {
           List<string> new_result = new List<string>();
           foreach (var element in target)
           {
               new_result.Add(element);
           }

           Results.Add(new_result);
       }
       return true;
}

Basically, dataConverter.getFromFile() will read from a CSV a string of information, and then read it into a List<List<string>>. I know this section works as I’ve been manually concatenating the data & printing it to a label on the front-end.

XAML

<ListView ItemsSource="{Binding Results}">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ListView ItemsSource="{Binding}">
                        <ListView.ItemTemplate>
                            <DataTemplate>
                                <TextBlock Text="{Binding}" />
                            </DataTemplate>
                     </ListView.ItemTemplate>
                </ListView>
         </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

The Output

It puts each element on a new “row”, whereas I want each List<string> as a series of “columns”.

So.. In essense:

  • There is a List<List<string>>
  • Each string inside List<string> should be a new column with the data inside
  • Each List<List<string>> should be a new row

Like so:

enter image description here

Example data:

  • A List<string> entry could equal: { “Test1”, “Test2”, “Test3” }
  • A Results is of the format List<List<string>> and would be a collection of these List<string> entries.

Not sure why I’m having so much trouble with this – but if anyone has the solution – it would be appreciated!

Please feel free to ask questions & sorry for the essay. 🙂

How to&Answers: