Saturday, 24 January 2009

How to center a listview column in Grid mode

This one I’ve really struggled with. I have a lot of listviews in the application, and basically I love listviews in WPF, but as I wrote earlier, the downside of having total control is that you must control everything…

I have some columns that I wanted to be centred. Actually, this is not very easy. I’ve used Goggle a bit, but mostly I’ve read the MSDN documentation and now after three hours of testing I’ve come up with a solution. I’m not really satisfied yet, but it will work for now.

First I thought that there would be some sort of HorizontalContentAlignment property I could set. But there isn’t any there for columns. So I started to style the column in the listview that I want to centre like this.

<Style x:Key="OnlineHeaderStyle" 
               TargetType="{x:Type GridViewColumnHeader}" 
> <Setter Property="HorizontalContentAlignment" Value="Center"/> </Style> <DataTemplate x:Key="OnlineCell"> <DockPanel> <TextBlock Foreground="DarkBlue" HorizontalAlignment="Center" TextAlignment="Center"> <TextBlock.Text> <Binding Path="Publish" Converter="{StaticResource
/> </TextBlock.Text> </TextBlock> </DockPanel> </DataTemplate>

This should do it I assumed, but it wasn’t enough. I also had to set a style for the ListView.ItemContainerStyle, like this:

<ListView Name="lv_Tournaments" 
   View="{StaticResource GridViewTournament}">
     <Style TargetType="ListViewItem">
      <Setter Property="HorizontalContentAlignment" 
Value="Stretch" /> </Style> </ListView.ItemContainerStyle> </ListView>

This has to be done because the Dockpanel, or all containers for a column cell has some sort of auto size, so if the cell is 100px wide, but the text of that cell if only 20px wide, the text container will be only 20px, and the textontainer is some how aligned to the left, and even tough the content is centred, it appears as left aligned, but with the HorizontalContentAlignment of the ItemcontainerStyle set to stretch the textcontainer will have a width of 100px, and the text will appear as centred. As i wrote in the beginning, I’m not total happy with this solution, but it is good enough for now. I can get it better, and will write about it then, and I also think that Microsoft has some things to develop regarding the Listview.

Labels: ,

kick it on


Post a Comment

Links to this post:

Create a Link

<< Home