我想在列中直观地表示我的数据,而不是DataGrid的行表示。您可以将我的数据视为List<Column>
,其中列包含List<Cell>
。我没有转置数据而只是使用DataGrid的原因是我希望能够动态添加/删除列,而不必处理所有数据。
+--------------------------------------------+
| | Col Header | Col Header | ... |
| Row Header | Cell | Cell | ... |
| ... | ... | ... | ... |
+--------------------------------------------+
我有一个xaml样本,几乎可以满足我的需求:
<StackPanel Orientation="Horizontal">
<StackPanel Orientation="Vertical" VerticalAlignment="Top">
<TextBox Text="" IsReadOnly="True" BorderThickness="0" HorizontalAlignment="Stretch"/>
<TextBox Text="" IsReadOnly="True" BorderThickness="0,0,0,2" BorderBrush="Black" HorizontalAlignment="Stretch"/>
<ItemsControl ItemsSource="{Binding RowHeaders}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Vertical"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBox Text="{Binding Mode=OneWay}" IsReadOnly="True" BorderThickness="0,0,2,2" BorderBrush="Black" FontWeight="Bold" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
<ItemsControl ItemsSource="{Binding Columns}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical" >
<TextBox Text="{Binding ColHead1, Mode=OneWay}" IsReadOnly="True" BorderThickness="0" FontWeight="Bold" HorizontalAlignment="Stretch"/>
<TextBox Text="{Binding ColHead2, Mode=OneWay}" IsReadOnly="True" FontWeight="Bold" BorderThickness="0,0,0,2" BorderBrush="Black" HorizontalAlignment="Stretch"/>
<ItemsControl ItemsSource="{Binding Cells}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Vertical" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBox x:Name="textBox" Text="{Binding}" IsReadOnly="{Binding IsReadOnly}" BorderThickness="0,0,0,2" BorderBrush="Black" HorizontalAlignment="Stretch"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
但是,如何确保我的行始终对齐?保证列中的单元格对齐,因为它们包含在单个ItemsControl中。但是,每列都在其自己的StackPanel中。有没有办法确保所有行都对齐?
此外,这似乎是解决问题的好方法,还是有更好的替代方案?