如何在wpf中将listView中的项目对齐到列的中间?

i2loujxw  于 2023-10-22  发布在  其他
关注(0)|答案(1)|浏览(182)

现在数字向左对齐。

我试着改变对中心的对齐,但它没有改变太多。

<Window x:Class="wpfMultiThreadListViewUpdate.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="500">
    <Grid>
        <Button Content="Update" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Margin="10,10,0,0" Click="btnUpdate_Click"/>
        <ListView x:Name="lstvwPeople" HorizontalAlignment="Left" VerticalAlignment="Top" Width="400" Height="250" Margin="10,40,0,0">
            <ListView.View>
                <GridView>
                    <GridViewColumn Header="Name" Width="200" DisplayMemberBinding="{Binding Name}"/>
                    <GridViewColumn Header="ID" Width="100">
                        <GridViewColumn.CellTemplate>
                            <DataTemplate>
                                <TextBlock Text="{Binding Id}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
                            </DataTemplate>
                        </GridViewColumn.CellTemplate>
                    </GridViewColumn>
                </GridView>
            </ListView.View>
        </ListView>
    </Grid>
</Window>

我也尝试将ID宽度值更改为150,但它没有改变任何东西。

goqiplq2

goqiplq21#

这是由于细胞的内容物被包裹在外部容器中。出于某种原因,默认情况下,WPF开发人员为外部容器选择了左对齐值。
您可能会对一个更改ListView中所有项目的默认值样式的解决方案感到满意:

<Grid>
        <Button Content="Update" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Margin="10,10,0,0" Click="btnUpdate_Click"/>
        <ListView x:Name="lstvwPeople" HorizontalAlignment="Left" VerticalAlignment="Top" Width="400" Height="250" Margin="10,40,0,0">
           <ListView.ItemContainerStyle>
               <Style TargetType="ListViewItem">
                   <Setter Property="HorizontalContentAlignment" Value="Stretch" />
               </Style>
            </ListView.ItemContainerStyle>
            <ListView.View>
                <GridView>
                    <GridViewColumn Header="Name" Width="200" DisplayMemberBinding="{Binding Name}"/>
                    <GridViewColumn Header="ID" Width="100">
                        <GridViewColumn.CellTemplate>
                            <DataTemplate>
                                <TextBlock Text="{Binding Id}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
                            </DataTemplate>
                        </GridViewColumn.CellTemplate>
                    </GridViewColumn>
                </GridView>
            </ListView.View>
        </ListView>
    </Grid>

**P.S.**就个人而言,我更喜欢使用具有IsReadOnly=true设置的DataGrid来完成此类任务。它在设置上更加方便和灵活。

相关问题