在ItemsControl的DataTemplate中绑定DataGrid

时间:2015-01-27 00:12:01

标签: wpf data-binding datagrid datatemplate

我遇到了一个奇怪的问题,我试图设置绑定。我有一个ItemsControl,我用它来渲染一个WrapPanel,它包含DataTemplate的DataGrid。最后,我想使用WrapPanel为列表中绑定到ItemsControl的每个项目显示一个DataGrid。现在它创建了正确数量的DataGrids和标头,但实际上没有绑定数据。我对WPF的经验不足以了解我在这里误入歧途的地方。这些项本身就是Tuple对象。为什么我的数据值没有受到约束?



<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>
&#13;
&#13;
&#13;

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 个答案:

答案 0 :(得分:0)

您的GetDistinctCodeCounts会为您提供IEnumerable < tuple < string, int > >

但你需要一个IEnumerable< IEnumerable< tuple < string,int>> >

小测试:将属性GetDistinctCodeCounts替换为:

   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),
            }
           );

我的测试:

enter image description here