Binding DataGrid Within A DataTemplate of ItemsControl

帅比萌擦擦* 提交于 2019-12-11 09:39:45

问题


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:



来源:https://stackoverflow.com/questions/28161157/binding-datagrid-within-a-datatemplate-of-itemscontrol

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!