Adding columns in WPF but only for certain rows

Viewed 24

I'm working on understanding the Grid control in WPF. I have a really basic setup here:

Screenshot of Visual Studio

What I would like is, instead of having three rows and three columns that divide up each row, I'd like to have the columns only dividing up the last row, so that the top two rows have no columns, and only the last (third) row has columns.

1 Answers

You can change the template of the DataGridRow for the rows that you want to make them look different..

Assume you've set the ItemsSource like this..

var allItems = new ObservableCollection<DataItem>();
// ..
// fill the collection with data
// ..
DataGridName.ItemsSource = allItems;

First, Add new property to DataItem class

public bool LooksDifferent { get; set; }

Next, In xaml, we will change the DataGridRow template when LooksDifferent is true..

<DataGrid ItemsSource="{Binding Items}">
    <DataGrid.ItemContainerStyle>
        <Style TargetType="{x:Type DataGridRow}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding LooksDifferent}" Value="True">
                    <Setter Property="Template">
                        <Setter.Value>
                            <ControlTemplate TargetType="{x:Type DataGridRow}">
                                <Border
                                    Background="White"
                                    BorderBrush="Black"
                                    BorderThickness="0,0,1,1">
                                    <TextBlock Text="I AM DIFFERENT" />
                                </Border>
                            </ControlTemplate>
                        </Setter.Value>
                    </Setter>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </DataGrid.ItemContainerStyle>

    <DataGrid.Columns>
        <DataGridTextColumn
            Width="*"
            Binding="{Binding Property1}"
            Header="Header1" />
        <DataGridTextColumn
            Width="*"
            Binding="{Binding Property2}"
            Header="Header2" />
    </DataGrid.Columns>
</DataGrid>

Now, You are all set! Give it a try..

Related