Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to center a TextBlock inside a GridViewColumn? (Sample xaml included)

<Window x:Class="EffectsWindow.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        DataContext="{Binding RelativeSource={RelativeSource Self}}">

    <ListView ItemsSource="{Binding EffectsViewModel.Effects}">
        <ListView.View>
            <GridView>
                <GridViewColumn Width="200" Header="Effects">
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <TextBlock HorizontalAlignment="Center"
                                       Text="{Binding Name}"
                                       TextAlignment="Center" />
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
            </GridView>
        </ListView.View>
    </ListView>

</Window>

Effect is just a type has a Name property that returns a string, but the text is still not centered inside its cell.

Any ideas on how to fix it?

like image 707
Joan Venge Avatar asked Mar 24 '11 20:03

Joan Venge


1 Answers

You can Stretch the HorizontalContentAlignment for ItemContainerStyle

<ListView ItemsSource="{Binding EffectsViewModel.Effects}">
    <ListView.ItemContainerStyle>
        <Style TargetType="ListViewItem">
            <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
        </Style>
    </ListView.ItemContainerStyle>
    <!--...-->
</ListView>

Update

You should be able to combine the alternating row colors with HorizontalContentAlignment like this. I tried it and it seems to be working

<ListView ItemsSource="{Binding EffectsViewModel.Effects}"
          AlternationCount="2">
    <ListView.ItemContainerStyle>
        <Style TargetType="ListViewItem">
            <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
            <Style.Triggers>
                <Trigger Property="ItemsControl.AlternationIndex" Value="1">
                    <Setter Property="Background" Value="LightBlue"></Setter>
                </Trigger>
                <Trigger Property="ItemsControl.AlternationIndex" Value="2">
                    <Setter Property="Background" Value="LightGray"></Setter>
                </Trigger>
            </Style.Triggers>
        </Style>
    </ListView.ItemContainerStyle>
    <!--...-->
</ListView>
like image 98
Fredrik Hedblad Avatar answered Sep 29 '22 07:09

Fredrik Hedblad