Search code examples
wpflistview

Setting different alignments for listview columns


I'm having trouble drawing a listview with columns that are left or centre aligned. I've looked at a few of solutions that I've found on here or other forums but they either seem to work for all columns or I can't get them working.

The best I've got so far is this code, but everything is left aligned (I've put the right-aligns in to test the code). Can someone tell me where I'm going wrong please?

<ListView Name="lsvQuestions" DockPanel.Dock="Bottom">                
     <ListView.View>
         <GridView>
             <GridViewColumn Width="450" Header="Question Text">
                 <GridViewColumn.CellTemplate>
                     <DataTemplate>
                         <TextBlock Text="{Binding QuestionText}" TextAlignment="Left"/>
                     </DataTemplate>
                 </GridViewColumn.CellTemplate>
                 </GridViewColumn>
                 <GridViewColumn Width="200" Header="Type">
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding QuestionType}" TextAlignment="Right"/>
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                 </GridViewColumn>
                 <GridViewColumn Width="100" Header="Page Number">
                     <GridViewColumn.CellTemplate>
                         <DataTemplate>
                             <TextBlock Text="{Binding QuestionPageNumber}" TextAlignment="Center"/>
                         </DataTemplate>
                     </GridViewColumn.CellTemplate>
                 </GridViewColumn>
                 <GridViewColumn Width="100" Header="Order">
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding QuestionOrder}" TextAlignment="Center"/>
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
            </GridView>
        </ListView.View>               
    </ListView>

Solution

  • Your ListViewItems don't stretch the content by default and that's why all items appear on the left. Add this and it will work:

    <ListView.ItemContainerStyle>
        <Style TargetType="ListViewItem">
            <Setter Property="HorizontalContentAlignment" Value="Stretch" />
        </Style>
    </ListView.ItemContainerStyle>