.net 如何在 WPF ListView 的特定列中居中文本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5098668/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 15:18:56  来源:igfitidea点击:

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

.netwpfxamllistviewstyling

提问by Joan Venge

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

我尝试了这个和 Horizo​​ntalAlignment,而不是 TextAlignment,但它们仍然显示为向左对齐。

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

回答by Fredrik Hedblad

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

尝试设置HorizontalContentAlignmentStretch了ItemContainerStyle。然后它应该与TextAlignment="Center"HorizontalAlignment="Center"一起工作TextBlock

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