c# - 如何使 TextBlock 在 GridViewColumn 中居中? (包括示例 xaml)

标签 c# .net wpf xaml layout

<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 属性的类型,但文本仍未在其单元格内居中。

关于如何修复它有什么想法吗?

最佳答案

您可以为 ItemContainerStyle 拉伸(stretch) Horizo​​ntalContentAlignment

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

更新

您应该能够像这样将交替行颜色与 Horizo​​ntalContentAlignment 结合起来。我试过了,它似乎有效

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

关于c# - 如何使 TextBlock 在 GridViewColumn 中居中? (包括示例 xaml),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5424922/

相关文章:

wpf - WPF图像,如何消除模糊?

c# - 将 DataGrid.ItemSsource 转换为 DataTable

wpf - WPF 数据绑定(bind)是否让事情变得比它的值(value)更痛苦?

c# - List、IList和IEnumerable的比较

.net - .NET BinaryReader 是否总是小端,即使在大端系统上?

c# - 您所见过的最好的WPF开源项目

c# - Microsoft.SqlServer.Types : Error loading msvcr120. dll(错误代码:5)

c# - C# 中的 ForEach 循环问题

c# - 跨页播放的音乐播放器

c# - 为什么私有(private)字段是类型私有(private)的,而不是实例私有(private)的?