且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

垂直合并WPF DataGrid中的单元格

更新时间:2023-02-04 20:03:31

这种情况的技巧是使用 Groups CollectionViewSource 中形成为 DataGrid ItemsSource 。并且,将 DataGrid 本身用作 CellTemplate

Trick to such scenarios is to use the Groups formed in CollectionViewSource as the ItemsSource of a DataGrid. And, use a DataGrid itself as the CellTemplate of Column.

Xaml

    <Window.Resources>
        <CollectionViewSource x:Key="CvsKey">
            <CollectionViewSource.GroupDescriptions>
                <PropertyGroupDescription PropertyName="Country"/>
            </CollectionViewSource.GroupDescriptions>
        </CollectionViewSource>
    </Window.Resources>

    <Grid>
        <DataGrid x:Name="dg" Loaded="dg_Loaded" HorizontalScrollBarVisibility="Disabled" HeadersVisibility="All" Grid.Column="0" RowHeaderWidth="0" CanUserAddRows="False" AutoGenerateColumns="False"  VerticalContentAlignment="Center" HorizontalContentAlignment="Center">            
            <DataGrid.Columns>
                <DataGridTemplateColumn Header="Country"  Width="75">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>                           
                            <Grid>
                                <TextBlock VerticalAlignment="Center" Text="{Binding Name}"/>
                            </Grid>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
                <DataGridTemplateColumn Header="Name"  Width="75">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <DataGrid ItemsSource="{Binding Items}" IsReadOnly="True" AutoGenerateColumns="False" HeadersVisibility="None">
                                <DataGrid.Columns>
                                    <DataGridTemplateColumn Width="*">
                                        <DataGridTemplateColumn.CellTemplate>
                                            <DataTemplate>
                                                <TextBlock Text="{Binding Name}"/>
                                            </DataTemplate>
                                        </DataGridTemplateColumn.CellTemplate>
                                    </DataGridTemplateColumn>
                                </DataGrid.Columns>
                            </DataGrid>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
          </DataGrid.Columns>            
        </DataGrid>
    </Grid>
</Window>

DataGrid.Loaded事件

 private void dg_Loaded(object sender, RoutedEventArgs e)
    {
        var groups = (this.Resources["CvsKey"] as CollectionViewSource).View.Groups;
        dg.ItemsSource = groups;
    }

这应该会让您入门。

输出: