WPF二维DataGrid/ListView? [英] WPF Two-dimensional DataGrid/ListView?
问题描述
我有一个由 3 列组成的表 Item
:
I have a table Item
that consists of 3 columns:
ItemId int PK
RoomId int FK
UnitId int FK
Cost money
我想要一个包含动态生成的列和行的 DataGrid/ListView,代表以下数据透视:
I want to have a DataGrid/ListView having dynamically-generated columns and rows representing the following pivot:
Room1 Room2 Room3 Room4
Unit1 $34 $72 $48 $98
Unit2 $64 $56 $67 $24
Unit3 $24 $34 $34 $34
我更喜欢现有的控件或助手而不是脏函数,因为我非常需要这种场景,但任何东西都受到热烈欢迎.
I prefer a control or a helper to an existing one rather than a dirty function since I am gonna need this scenario a lot, but anything at all is warmly welcommed.
我希望将 Room1
和 Unit1
等作为行和列标题,并相应地生成/设置单元格.
I want to have the Room1
and the Unit1
etc. as row and column headers, and the cells generated/set accordingly.
推荐答案
首先,您需要将 Item
对象的集合转换为合适的集合:
Firstly, you'd need to convert your collection of Item
objects into a suitable collection:
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);
然后你需要一个带有正确DataTemplate
配置的ItemsControl
and then you need an ItemsControl
with the correct DataTemplate
configuration
<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>
然后你会得到这个:
这篇关于WPF二维DataGrid/ListView?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!