Search code examples
wpftemplatesdatagridcolumnheader

How to set datagrid columnheader to show both icon and text?


I have a datagrid in my WPF app and I want to show a redlight icon on some columns to demonstrate that the column is missing some data. This is my window resource in XAML:

<DataTemplate x:Key="RedTemp">
    <Image Source="/MyApp;component/Images/red.png"
           Height="9"
           Width="9"
           HorizontalAlignment="Right" />
</DataTemplate>

and this is how I call it from code behind:

foreach (DataGridColumn y in grid.Columns)
{
    if (Missing== 1)
    {
        y.HeaderTemplate = FindResource("RedTemp") as DataTemplate;
    }              
}

But when I run the app, the datagrid shows red lights on columns but the Column Header Text disappears!

Any ideas how to fix this problem?


Solution

  • You should modify your DataTemplate to have a TextBlock with your text, something like:

    <DataTemplate x:Key="RedTemp">
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition />
                <ColumnDefinition />
            </Grid.ColumnDefinitions>
            <TextBlock Text="{TemplateBinding Content}"  />
            <Image Source="/MyApp;component/Images/red.png"
                   Height="9"
                   Width="9"
                   HorizontalAlignment="Right"
                   Grid.Column="1"
                   />
         </Grid>
    </DataTemplate>
    

    I haven't tested this though.

    Edit: Added a Panel around 2 UI Elements.