user2023861
user2023861

Reputation: 8208

How do I customize the display of column headers in my WPF Datagrid?

I am trying to customize a DataGrid. I want to insert some content above the column headers. I am trying to use the ControlTemplate to do this. I have my XAML code below. My problem is that the <ContentPresenter /> is not outputting anything. When I load the page, the after TextBlock appears directly below the before TextBlock with nothing in between. I want to display the column headers in that space.

<DataGrid ItemsSource="{Binding List}" AutoGenerateColumns="True">

    <DataGrid.Template>
        <ControlTemplate>
            <StackPanel Orientation="Vertical">
                <TextBlock>before</TextBlock>
                <ContentPresenter /> <!-- outputs nothing -->
                <TextBlock>after</TextBlock>                        
                <ItemsPresenter />
            </StackPanel>
        </ControlTemplate>
    </DataGrid.Template>

</DataGrid>

How do I display the column headers between the before TextBlock and the after TextBlock? My List object is simply a BindingList of some generic class that has a couple of public properties.

Upvotes: 0

Views: 962

Answers (1)

user2023861
user2023861

Reputation: 8208

I found the answer. I should use <DataGridColumnHeadersPresenter /> instead of <ContentPresenter />. So my code that works looks like:

<DataGrid ItemsSource="{Binding List}" AutoGenerateColumns="True">

    <DataGrid.Template>
        <ControlTemplate>
            <StackPanel Orientation="Vertical">
                <TextBlock>before</TextBlock>
                <DataGridColumnHeadersPresenter />
                <TextBlock>after</TextBlock>
                <ItemsPresenter />
            </StackPanel>                        
        </ControlTemplate>
    </DataGrid.Template>

</DataGrid>

Upvotes: 2

Related Questions