我可以轻松地在基本(非 GridView)模式下“隐式”设置 ListView 的样式,但我尝试在 GridView 模式下隐式设置 ListView 的样式却惨遭失败。下面的工作是因为我明确设置了第二个 ListView 的 Style 和 ItemContainerStyle。如果您删除这两个设置,则第二个 ListView 不会像第一个那样获得隐式样式。似乎一个基本的 ListView 需要一个 ContentPresenter,而一个 GridView ListView 需要一个 GridViewRowPresenter。
我在这里遇到了 WPF 砖墙吗?这甚至可能吗?如果没有,它会降低创建应用程序外观的健壮性,因为现在您的用户必须知道在 GridView 模式下显示的 ListView 上显式设置 Style 和 ItemContainerStyle。
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:system="clr-namespace:System;assembly=mscorlib"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<Style TargetType="ListView">
<Setter Property="Background" Value="Lime"/>
</Style>
<Style TargetType="ListViewItem">
<Setter Property="Background" Value="Yellow"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBoxItem}">
<Grid>
<ContentPresenter x:Name="ContentHost" Margin="{TemplateBinding Padding}"
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}" />
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style x:Key="{x:Static GridView.GridViewStyleKey}"
TargetType="{x:Type ListView}">
<Setter Property="Background" Value="Lime"/>
</Style>
<Style x:Key="{x:Static GridView.GridViewItemContainerStyleKey}"
TargetType="{x:Type ListViewItem}">
<Setter Property="Background" Value="Yellow"/>
</Style>
</Window.Resources>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<ListView x:Name="_listView1">
<system:String>Item 1</system:String>
<system:String>Item 2</system:String>
<system:String>Item 3</system:String>
</ListView>
<ListView x:Name="_listView2" Grid.Column="1"
Style="{StaticResource {x:Static GridView.GridViewStyleKey}}"
ItemContainerStyle="{StaticResource {x:Static GridView.GridViewItemContainerStyleKey}}">
<ListView.View>
<GridView>
<GridViewColumn Header="Date"/>
<GridViewColumn Header="Day of Week" DisplayMemberBinding="{Binding DayOfWeek}" />
<GridViewColumn Header="Year" DisplayMemberBinding="{Binding Year}" />
</GridView>
</ListView.View>
<system:DateTime>1/1/2010</system:DateTime>
<system:DateTime>1/1/2011</system:DateTime>
<system:DateTime>1/1/2012</system:DateTime>
</ListView>
</Grid>
</Window>