Silverlight DataGrid – custom DataGridColumnHeaders

The easiest way to have any type of content appear in the DataGrid column header is to set the ContentTemplate style.

                <sdk:DataGridTextColumn Binding="{Binding PartNumber}" IsReadOnly="True">
                    <sdk:DataGridTextColumn.HeaderStyle>
                        <Style TargetType="dataprimitives:DataGridColumnHeader">
                            <Setter Property="ContentTemplate">
                                <Setter.Value>
                                    <DataTemplate>
                                        <StackPanel>
                                            <TextBlock>Part</TextBlock>
                                            <TextBlock>Number</TextBlock>
                                        </StackPanel>
                                    </DataTemplate>
                                </Setter.Value>
                            </Setter>
                        </Style>
                    </sdk:DataGridTextColumn.HeaderStyle>
                </sdk:DataGridTextColumn>

The problem begins when you have themed your DataGrid to remove the blue gradient in the header. Whenever you set the HeaderStyle on a template, you need to reference the HeaderStyle defined in your theme. Unfortunately, I couldn’t make the following work:

            <Style x:Key="ServiceDayHeader" 
                   TargetType="dataprimitives:DataGridColumnHeader"
                   BasedOn="{StaticResource dataprimitives:DataGridColumnHeader}">
                
            </Style>

This I managed to work around by setting BasedOn during InitializeComponent.

        public ServiceDay()
        {
            this.InitializeComponent();
System.ComponentModel.PropertyChangedEventHandler(ServiceDayModelDataSource_PropertyChanged);
            SetHeaderStyle();
        }

        void SetHeaderStyle()
        {
            Style parentStyle = (Style)Application.Current.Resources[typeof(DataGridColumnHeader)];
            foreach (var key in this.Resources.Keys)
            {
                Style style = this.Resources[ key] as Style;
                if (style != null && style.TargetType == typeof(DataGridColumnHeader))
                {
                    if (!style.IsSealed && style.BasedOn == null)
                    {
                        style.BasedOn = parentStyle;
                    }
                }
            }
        }

About this entry