如何在GridViewColumn中使TextBlock居中?(包含示例xaml)

5
<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 是一个类型,具有一个返回字符串的 Name 属性,但文本仍未居中显示在其单元格内。

有什么解决办法吗?

2个回答

5
您可以拉伸ItemContainerStyleHorizontalContentAlignment
<ListView ItemsSource="{Binding EffectsViewModel.Effects}">
    <ListView.ItemContainerStyle>
        <Style TargetType="ListViewItem">
            <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
        </Style>
    </ListView.ItemContainerStyle>
    <!--...-->
</ListView>

更新

您可以像这样将交替行颜色与 HorizontalContentAlignment 结合使用。我尝试过,它似乎可以正常工作。

<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>

1
谢谢,但是那段代码会将所有的ListViewItems都居中对齐,对吧?我只想让某些列居中对齐,其他列则按原样(左对齐)。 - Joan Venge
1
@Joan Venge:如果您设置了 HorizontalAlignment="Center",它将居中列,否则它将左对齐(或者您指定的任何对齐方式)。 - Fredrik Hedblad
Meleak,这个方法很好用。谢谢,但是有一个小问题。基本上我使用这种交替颜色:http://blogs.msdn.com/b/vinsibal/archive/2008/05/28/wpf-3-5-sp1-feature-alternating-rows.aspx 那里的第一个xaml示例也设置了样式,所以它们似乎不能同时工作。是否可能将它们结合起来? - Joan Venge
1
@Joan Venge:我更新了我的回答。如果我正确理解了你的问题,那应该可以。 - Fredrik Hedblad
1
谢谢Meleak,它非常有效。我一直在尝试看看在现有的交替样式中如何适应您的代码,但无法做到。感谢您展示如何实现这一点。 - Joan Venge

0

尝试使用像snoop这样的应用程序来直观地检查您的应用程序属性,您可以看到哪些地方与您的期望不符。


谢谢,我试过了,但仍然没有帮助我使其居中。 - Joan Venge

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接