How to center text in a specific column in WPF ListView?

27,390

Try to set HorizontalContentAlignment to Stretch for the ItemContainerStyle. Then it should work with either TextAlignment="Center" or HorizontalAlignment="Center" for the TextBlock

<ListView ItemsSource="{Binding Effects}">
    <ListView.ItemContainerStyle>
        <Style TargetType="ListViewItem">
            <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
        </Style>
    </ListView.ItemContainerStyle>
    <!--...-->
</ListView>
Share:
27,390

Related videos on Youtube

Joan Venge
Author by

Joan Venge

Professional hitman.

Updated on July 09, 2022

Comments

  • Joan Venge
    Joan Venge almost 2 years

    I tried this and also HorizontalAlignment, instead of TextAlignment but they still show up aligned to left.

    <Window x:Class="EditorWindow.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            DataContext="{Binding RelativeSource={RelativeSource Self}}"
            Title="MainWindow" Height="800" Width="600">
        <Grid>
            <ListView ItemsSource="{Binding Effects}">
                <ListView.View>
                    <GridView>
                        <GridViewColumn Width="100" Header="Name" DisplayMemberBinding="{Binding Name}"  />
                        <GridViewColumn Width="100" Header="Type" >
                            <GridViewColumn.CellTemplate >
                                <DataTemplate>
                                    <TextBlock Text="{Binding Type}" TextAlignment="Center"/>
                                </DataTemplate>
                            </GridViewColumn.CellTemplate>
                        </GridViewColumn>
                        <GridViewColumn Width="100" Header="Opacity" DisplayMemberBinding="{Binding Opacity}" />
                    </GridView>
                </ListView.View>
            </ListView>
        </Grid>
    </Window>
    
  • ShadowScripter
    ShadowScripter almost 11 years
    Brilliant. Could someone explain why you have to do this in order for it to work?
  • Gaurav123
    Gaurav123 almost 10 years
    How to do the same for specific columns only
  • Gaurav123
    Gaurav123 almost 10 years
    I used <GridViewColumn Header="Exact Date" Width="100"> <GridViewColumn.CellTemplate > <DataTemplate> <TextBlock Text="{Binding Path=ExactDate, StringFormat='MM/dd/yyyy'}" TextAlignment="Right" HorizontalAlignment="Right"/> </DataTemplate> </GridViewColumn.CellTemplate> </GridViewColumn> but it did not work
  • Filip
    Filip about 7 years
    don't forget to remove the DisplayMemberBinding attribute off the column, or the CellTemplate won't get applied at all