Categories: Silverlight 2 Tips Posted on 5/4/2009 12:03 PM by Ryan Shelby  Feedback (0)

Last week I had a hard time finding a clear answer to what seemed to be a simple and common task, so I wrote down the solution I came up with here.  The easiest way to center the header text in a Silverlight Datagrid Column is to do it code behind:

 

    1 'Create new header style - add setters.
    2  Dim myStyle As New Style(GetType(DataGridColumnHeader))
    3  myStyle.Setters.Add(New Setter(HorizontalContentAlignmentProperty, HorizontalAlignment.Center))
    4 
    5  'Use column index for specific columns.
    6   myDataGrid.Columns(1).HeaderStyle = myStyle
    7 
    8   'Use ColumnHeaderStyle Property for all columns:
    9   myDataGrid.ColumnHeaderStyle = myStyle

 

 

If you want to do it all entirely through XAML, then it's a bit more complicated.  Below shows the entire example:

 

    1 <UserControl x:Class="MySolution.Page" 
    2              xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    3              xmlns:my="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data" 
    4              xmlns:prim="clr-namespace:System.Windows.Controls.Primitives;assembly=System.Windows.Controls.Data" 
    5              xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    6 
    7     <UserControl.Resources>
    8         <Style x:Name="CenterHeaderText" TargetType="prim:DataGridColumnHeader">
    9             <Setter Property="HorizontalContentAlignment" Value="Center" />
   10         </Style>
   11     </UserControl.Resources>
   12 
   13     <my:DataGrid x:Name="myDataGrid" AutoGenerateColumns="False" HeaderStyle="{StaticResource CenterHeaderText}">
   14         <my:DataGrid.Columns>
   15             <my:DataGridTextColumn Header="Column 1" Binding="{Binding Column1Data}" />
   16             <my:DataGridTextColumn Header="Column 2" Binding="{Binding Column2Data}" />
   17             <my:DataGridTextColumn Header="Column 3" Binding="{Binding Column3Data}" />
   18         </my:DataGrid.Columns>
   19     </my:DataGrid>
   20 
   21 </UserControl>

 

Comments

Send Feedback





biuquote
  • Comment
  • Preview
Loading