user2529011
user2529011

Reputation: 743

Add filter buttons to datagrid column headers

I have a working datagrid and I'm exploring ways to add a filter button to my header columns much like how the new Excel does it. The rough sketch below demonstrates the desired functionality. Ideally the button would appear in the top right, if clicked once it would show an itemBox (or something more appropriately) and if clicked again it would close the itemBox.

enter image description here

So far I've been trying to add a button (step 1) to the Connection Status column but its not coming up.

<DataGridTemplateColumn Header="ConnectionStatus" MinWidth="33">
                    <DataGridTemplateColumn.HeaderStyle>
                        <!--THIS IS WHERE IM TRYING TO ADD THIS BUTTON-->
                    </DataGridTemplateColumn.HeaderStyle>
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <Ellipse Height="15" Width="15" StrokeThickness="2" HorizontalAlignment="Center" VerticalAlignment="Center" Style="{StaticResource OnlineStatusConverterStyle}"/>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>

My question is how do i set up my headers in order to get a button to show up?

Upvotes: 0

Views: 5138

Answers (1)

Keith Stein
Keith Stein

Reputation: 6754

I would use DataGridColumn.HeaderTemplate. You can make a reusable DataTemplate and leave the Header property for the actual content. Here's a quick example I threw together:

<DataGrid>
    <DataGrid.Resources>
        <DataTemplate x:Key="HeaderTemplate">
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition/>
                    <ColumnDefinition Width="Auto"/>
                </Grid.ColumnDefinitions>

                <ContentControl Content="{Binding}" VerticalAlignment="Center"/>
                <ToggleButton Name="FilterButton" Grid.Column="1" Content="▼" Margin="2, 1, 1, 1" Padding="1, 0"/>
                <Popup IsOpen="{Binding ElementName=FilterButton, Path=IsChecked}" PlacementTarget="{Binding ElementName=FilterButton}" StaysOpen="False">
                    <Border Background="White" Padding="3">
                        <TextBlock>Some Filters Here</TextBlock>
                    </Border>
                </Popup>
            </Grid>
        </DataTemplate>
    </DataGrid.Resources>

    <DataGrid.Columns>
        <DataGridTemplateColumn Header="Column 1" HeaderTemplate="{StaticResource HeaderTemplate}"/>
        <DataGridTemplateColumn Header="Column 2" HeaderTemplate="{StaticResource HeaderTemplate}"/>
    </DataGrid.Columns>
</DataGrid>

Upvotes: 3

Related Questions