.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
How to center text in a specific column in WPF ListView?
提问by Joan Venge
I tried this and also HorizontalAlignment, instead of TextAlignment but they still show up aligned to left.
我尝试了这个和 HorizontalAlignment,而不是 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
尝试设置HorizontalContentAlignment到Stretch了ItemContainerStyle。然后它应该与TextAlignment="Center"或HorizontalAlignment="Center"一起工作TextBlock
<ListView ItemsSource="{Binding Effects}">
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
</Style>
</ListView.ItemContainerStyle>
<!--...-->
</ListView>

