WPF二维DataGrid / ListView?

时间:2010-11-22 23:14:06

标签: wpf listview datagrid pivot-table multidimensional-array

我有一个由{3}组成的表Item

ItemId int PK
RoomId int FK
UnitId int FK
Cost money

我希望DataGrid / ListView具有动态生成的列和行,代表以下数据透视:

       Room1 Room2 Room3 Room4 
Unit1  $34   $72   $48   $98
Unit2  $64   $56   $67   $24
Unit3  $24   $34   $34   $34

我更喜欢控制或帮助现有的而不是脏功能,因为我需要这个场景很多,但任何事情都是热烈欢迎的。

我想将Room1Unit1等作为行和列标题,并相应地生成/设置单元格。

1 个答案:

答案 0 :(得分:8)

首先,您需要将Item个对象的集合转换为合适的集合:

var dict = data.Select(i => i.UnitId).Distinct()
    .ToDictionary(u =>  u, u => data
        .Where(i => i.UnitId == u)
        .ToDictionary(d => d.RoomId, d => d));
var rooms = dict.Values.First().Keys;
DataContext = Tuple.Create(dict, rooms);

然后您需要ItemsControl具有正确的DataTemplate配置

<Grid>
  <Grid.RowDefinitions>
    <RowDefinition Height="Auto" />
    <RowDefinition Height="Auto" />
  </Grid.RowDefinitions>
  <ItemsControl ItemsSource="{Binding Item2}">
    <ItemsControl.ItemsPanel>
      <ItemsPanelTemplate>
        <StackPanel Orientation="Horizontal"
                    Margin="80,0,0,0" />
      </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
      <DataTemplate>
        <TextBlock HorizontalAlignment="Center"
                   Foreground="Blue"
                   Width="80"
                   Margin="5">
                        <Run Text="Room" />
                        <Run Text="{Binding Mode=OneWay}" />
        </TextBlock>
      </DataTemplate>
    </ItemsControl.ItemTemplate>
  </ItemsControl>
  <ItemsControl ItemsSource="{Binding Item1}"
                AlternationCount="{Binding Count}"
                Grid.Row="1">
    <ItemsControl.ItemTemplate>
      <DataTemplate>
        <StackPanel Orientation="Horizontal">
          <TextBlock VerticalAlignment="Center"
                     Foreground="Blue"
                     Width="80">
                        <Run Text="Unit" />
                        <Run Text="{Binding Key, Mode=OneWay}" />
          </TextBlock>
          <ItemsControl ItemsSource="{Binding Value}"
                        VerticalAlignment="Center">
            <ItemsControl.ItemsPanel>
              <ItemsPanelTemplate>
                <StackPanel Orientation="Horizontal" />
              </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
            <ItemsControl.ItemTemplate>
              <DataTemplate>
                <TextBlock Text="{Binding Path=Value.Cost, StringFormat={}{0:C}}"
                           Margin="5"
                           Width="80" />
              </DataTemplate>
            </ItemsControl.ItemTemplate>
          </ItemsControl>
        </StackPanel>
      </DataTemplate>
    </ItemsControl.ItemTemplate>
  </ItemsControl>
</Grid>

然后你明白了:

alt text