In general case, the header/title of a WPF ListView/GridView columns are aligned in the center and hence in many cases you will need to align the column header/title to left or right (based as per your business requirement).

 

Today we will learn how to do this in the XAML itself by creating a proper style for the column header. Continue reading to know the trick.

 

How to align the column header in a WPF ListView-GridView control (www.kunal-chowdhury.com)

 

The WPF ListView/GridView control does not expose any direct property to align the column header/title to left or right. By default, they are always center aligned. But in case you want to change the alignment, you need to do some tricks to the 'GridViewColumnHeader' style in the XAML.

 

Using a style with a TargetType of 'GridViewColumnHeader', you can set the value of the 'HorizontalContentAlignment' property of the header. This way, you will be able to control the header alignment in a WPF ListView/GridView control.

 

Let's see, how to do this by just placing a single setter to the style element of the control type ‘GridViewColumnHeader’. Here's the code for your reference:

 

<Style TargetType="{x:Type GridViewColumnHeader}">
    <Setter Property="HorizontalContentAlignment" Value="Left" />
</Style>

 

The above code will work globally within the scope. If you put it in the 'Resources' tag of the Window, scope will be limited to all the ListView/GridView controls available in that Window. If you put it in the 'Resources' tag of a specific ListView/GridView control, it will be only tagged to that specific control. In second case, rest of the controls will have the default view.

 

This is how it looks by default (center align):

WPF ListView-GridView control - Column Header aligned Center by default (www.kunal-chowdhury.com) 

 

This is how it will look after applying our style (left align):

WPF ListView-GridView control - Column Header aligned Left (www.kunal-chowdhury.com)

 

In case you want to give a different alignments to different columns, create multiple template style for individual alignments (MAX: 3 - Left, Right, Center) and give them a name (x:Key). Then assign the specific template style to the specific column respectively by using the StaticSource binding. That's all. Now run your application and check the output.

 

Hope that the post was helpful. Don’t miss my other posts on the WPF ListView/GridView control that I published recently. Here’s the links for your easy reference:

 

 

Have a question? Or, a comment? Let's Discuss it below...

dhgate

Thank you for visiting our website!

We value your engagement and would love to hear your thoughts. Don't forget to leave a comment below to share your feedback, opinions, or questions.

We believe in fostering an interactive and inclusive community, and your comments play a crucial role in creating that environment.