Binding DataGrid Within A DataTemplate of ItemsCon

2019-08-14 16:09发布

问题:

I have a strange issue occurring with the binding I'm trying to set up. I have an ItemsControl which I'm using to render a WrapPanel which contains a DataGrid for its DataTemplate. Ultimately I want to use the WrapPanel to show one DataGrid for each item in the list that gets bound to the ItemsControl. Right now it creates the correct number of DataGrids and headers, but there is no data actually being bound. I'm not experienced enough with WPF to know where I'm going astray here. The items themselves are Tuple objects. Why aren't my data values getting bound?

<ItemsControl ItemsSource="{Binding Path=GetDestinctCodeCounts}" Grid.Row="2" Grid.ColumnSpan="6" HorizontalAlignment="Center" HorizontalContentAlignment="Stretch">
  <ItemsControl.Template>
    <ControlTemplate>
      <WrapPanel IsItemsHost="True" />
    </ControlTemplate>
  </ItemsControl.Template>
  <ItemsControl.ItemTemplate>
    <DataTemplate>
      <DataGrid AutoGenerateColumns="False" IsReadOnly="True" Margin="2,0,2,2" ItemsSource="{Binding}">
        <DataGrid.Columns>
          <DataGridTextColumn Width="Auto" Binding="{Binding Item1}" Header="Code" />
          <DataGridTextColumn Width="Auto" Binding="{Binding Item2}" Header="Count" />
        </DataGrid.Columns>
      </DataGrid>
    </DataTemplate>
  </ItemsControl.ItemTemplate>
</ItemsControl>

public List<Tuple<string, int>> GetDestinctCodeCounts
    {
        get
        {
            if (UnQualifiedZips.Count > 0)
            {
                var distinctCount = UnQualifiedZips.GroupBy(x => x.Item2).Select(x => new Tuple<string, int>(x.Key, x.Count())).ToList();
                return distinctCount;
            }
            else return new System.Collections.Generic.List<Tuple<string, int>>();
        }
    }

回答1:

Your GetDistinctCodeCounts gives you an IEnumerable < tuple < string, int > >.

But you need an IEnumerable< IEnumerable< tuple < string,int>> >

Small test: Replace the property GetDistinctCodeCounts with this:

   List<List<Tuple<string, int>>> tuples = new List<List<Tuple<string, int>>>();
        tuples.Add(
            new List<Tuple<string, int>>()
            {
             new Tuple<string,int>("a",1),
             new Tuple<string,int>("b",2),
            }
            );

        tuples.Add(
           new List<Tuple<string, int>>()
            {
             new Tuple<string,int>("a",1),
             new Tuple<string,int>("b",2),
            }
           );

My test: