我认为您需要使用 a<ControlTemplate>
而不是 a <DataTemplate>
。我会把你的上述风格写成:
<Style x:Key="SelectorPanelListBoxStyle" TargetType="{x:Type ListBox}">
<Setter Property="Background" Value="{x:Null}"/>
<Setter Property="Foreground" Value="White"/>
<Setter Property="Border.CornerRadius" Value="2"/>
<Setter Property="ItemTemplate" x:Name="MyItemTemplate">
<Setter.Value>
<ControlTemplate>
<Border BorderBrush="White" BorderThickness="1" CornerRadius="5" OverridesDefaultStyle="True">
<Grid Height="57" Width="145">
<Label Content="{TemplateBinding Content}" />
<ContentControl Content="{Binding}" Foreground="White" />
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
下面是我自己的 ListBox 样式之一,以防它对您有所帮助:
<Style TargetType="{x:Type ListBox}">
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
<Setter Property="VerticalContentAlignment" Value="Center"/>
<Setter Property="AllowDrop" Value="True"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBox}">
<Border BorderThickness="0">
<ScrollViewer Margin="0">
<StackPanel Margin="0" IsItemsHost="True"/>
</ScrollViewer>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<DataTemplate x:Key="GridViewTemplate">
<Border BorderBrush="LightBlue" BorderThickness="0" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" CornerRadius="0">
<Grid VerticalAlignment="Stretch" HorizontalAlignment="Stretch">
<DockPanel VerticalAlignment="Stretch" HorizontalAlignment="Stretch">
<TextBlock FontFamily="Segoe UI Light" FontSize="18" Text="{Binding PropFullName}" Margin="2,2,2,2" DockPanel.Dock="Top"/>
<TextBlock FontFamily="Segoe UI Light" FontSize="18" Text="{Binding PropTitle}" Margin="2,2,2,2" DockPanel.Dock="Top"/>
</DockPanel>
</Grid>
</Border>
</DataTemplate>
然后按如下方式设置 DataTemplate:
<ListBox.ItemTemplate>
<StaticResource ResourceKey="GridViewTemplate"/>
</ListBox.ItemTemplate>
编辑1:
<DataTemplate x:Key="MyListBoxTemplate">
<Border BorderBrush="White" BorderThickness="1" CornerRadius="5" OverridesDefaultStyle="True">
<Grid Height="57" Width="145">
<Label Content="{TemplateBinding Content}" />
<ContentControl Content="{Binding}" Foreground="White" />
</Grid>
</Border>
</DateTemplate>
<Style TargetType="{x:Type ListBox}">
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
<Setter Property="VerticalContentAlignment" Value="Center"/>
<Setter Property="AllowDrop" Value="True"/>
<Setter Property="ItemTemplate">
<Setter.Value>
<StaticResource ResourceKey="MyListBoxItemTemplate"
</Setter.Value>
</Setter>
</Style>