How Do I Center Something In My ListView Column?

So the items in your ListView column look like this:

Centered Example 1

And you want them to look like this:

Centered Example 2

If you’re trying to center something within a ListView column, it’s actually pretty simple.

First, go to your ListView and, if you haven’t already, create an ItemContainerStyle by going to the Object -> Edit Other Styles… -> Edit ItemContainerStyle -> Create Empty…

ItemContainerStyle Menu

Within your ItemContainerStyle, set the HorizontalContentAlignment from “Left” to “Stretch“.

Your ItemContainerStyle XAML should now look like this (important stuff in bold):

<Style x:Key=”MyItemContainerStyle TargetType=”{x:Type ListViewItem}>
      <Setter Property=”HorizontalContentAlignment Value=”Stretch/>
</Style>

A point of note: if you want everything to be centered, you can set it to “Center“. However, if you prefer more control over the layout of your columns (as I do), set it to stretch.

Now, go to the DataTemplate for the column you want to center. (If you don’t know how to get to the DataTemplate or how to create one, you can find that information here. Just look for “DataTemplate”.)

Within the DataTemplate, align your bound item so that the HorizontalAlignment is set to “Center“.

Your DataTemplate should now look something like this (important stuff in bold):

<DataTemplate x:Key=”AuthorTemplate>
      <TextBlock Text=”{Binding Mode=OneWay, XPath=author}FontSize=”12”  HorizontalAlignment=”Center />
</DataTemplate>

Finally, your ListView should already be set up, but just to double check, make sure that your ListView XAML looks something like this:

<ListView ItemContainerStyle=”{DynamicResource MyItemContainerStyle} >
      <ListView.View>
            <GridView>
                  <GridViewColumn CellTemplate=”{DynamicResource AuthorTemplate} Header=”Author/>
            </GridView>
      </ListView.View>
</ListView>

3 Comments

  1. Designer WPF » Blog Archive » Styling A ListView Column Using Blend:

    [...] the image it points to shows up in the column instead of the stupid image source? (coming soon) How do I center something in my ListView column?  Category: Blend, How To…, XAML, listview  |  Comment (RSS) [...]

  2. prabha:

    selecting items from a particular column in a listview

    bold the items of a particular column in a listview

  3. Nick:

    @prabha

    If you have heard of Styling in WPF then it can be done using styling….

    Author also have few good articles regarding Styles and Templates…

    http://www.designerwpf.com/category/styles/
    http://www.designerwpf.com/category/templates/

    I am not going to post the code here coz I don’t know if author likes code posting in the comments or not

Leave a comment