TOC

This article has been localized into Chinese by the community.

ListView控件:

使用方法-列名称左对齐的ListView

在普通的ListView中,列名左对齐,但由于某种原因,Microsoft决定默认将名称置于WPF ListView中心。在许多情况下,与其他Windows应用程序相比,这将使您的应用程序看起来不合时宜。这是默认情况下ListView在WPF中的外观:

让我们尝试将其更改为左对齐的列名称。遗憾的是,GridViewColumn上没有直接属性来控制它,但幸运的是,这并不意味着它无法更改。

使用以GridViewColumHeader为目标的Style,它是用于显示GridViewColumn标题的元素,我们可以更改Horizo​​ntalAlignment属性。在这种情况下,它默认为Center,但我们可以将其更改为Left,以实现我们想要的目标:

<Window x:Class="WpfTutorialSamples.ListView_control.ListViewGridViewSample"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="ListViewGridViewSample" Height="200" Width="400">
    <Grid>
		<ListView Margin="10" Name="lvUsers">
			<ListView.Resources>
				<Style TargetType="{x:Type GridViewColumnHeader}">
					<Setter Property="HorizontalContentAlignment" Value="Left" />
				</Style>
			</ListView.Resources>
			<ListView.View>
				<GridView>
					<GridViewColumn Header="Name" Width="120" DisplayMemberBinding="{Binding Name}" />
					<GridViewColumn Header="Age" Width="50" DisplayMemberBinding="{Binding Age}" />
					<GridViewColumn Header="Mail" Width="150" DisplayMemberBinding="{Binding Mail}" />
				</GridView>
			</ListView.View>
		</ListView>
	</Grid>
</Window>

为我们完成所有工作的部分是ListView的Resources中定义的Style:

<Style TargetType="{x:Type GridViewColumnHeader}">
					<Setter Property="HorizontalContentAlignment" Value="Left" />
</Style>

本地或全局风格

通过在控件本身中定义Style,它仅适用于此特定的ListView。在许多情况下,您可能希望将其应用于同一窗口/页面中的所有ListView,或者甚至应用于整个应用程序的全局ListView。您可以通过将样式复制到Window资源或应用程序资源来完成此操作。这是相同的示例,我们将样式应用于整个Window而不仅仅是特定的ListView:

<Window x:Class="WpfTutorialSamples.ListView_control.ListViewGridViewSample"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="ListViewGridViewSample" Height="200" Width="400">
	<Window.Resources>
		<Style TargetType="{x:Type GridViewColumnHeader}">
			<Setter Property="HorizontalContentAlignment" Value="Left" />
		</Style>
	</Window.Resources>
	<Grid>
		<ListView Margin="10" Name="lvUsers">
			<ListView.View>
				<GridView>
					<GridViewColumn Header="Name" Width="120" DisplayMemberBinding="{Binding Name}" />
					<GridViewColumn Header="Age" Width="50" DisplayMemberBinding="{Binding Age}" />
					<GridViewColumn Header="Mail" Width="150" DisplayMemberBinding="{Binding Mail}" />
				</GridView>
			</ListView.View>
		</ListView>
	</Grid>
</Window>

如果你想要另一个对齐,例如右对齐,您只需更改样式的值,如下所示:

<Setter Property="HorizontalContentAlignment" Value="Right" />
This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!