SelectedItem的Horizo​​ntalContentAlignment没有完美拉伸

时间:2010-09-30 18:40:30

标签: wpf styles

我在WPF中制作了自定义样式列表:

                             

        <DataTemplate x:Key="SelectedTemplate">
            <StackPanel Background="#FF4E4E4E" HorizontalAlignment="Stretch">
                <TextBlock Text="{Binding Path=Title}" Foreground="#FFD80000" />
            </StackPanel>
        </DataTemplate>

        <Style TargetType="{x:Type ListBoxItem}" x:Key="ContainerStyle">
            <Setter Property="ContentTemplate" 
                    Value="{StaticResource ItemTemplate}" />
            <Setter Property="HorizontalContentAlignment" Value="Stretch" />
            <Style.Triggers>
                <Trigger Property="IsSelected" Value="True">
                    <Setter Property="ContentTemplate"
                            Value="{StaticResource SelectedTemplate}" />
                </Trigger>
            </Style.Triggers>
        </Style>

...

    <ListBox 
        Name="lbSongs"
        DockPanel.Dock="Left" 
        ItemsSource="{Binding Path=SongDirectory}"
        SelectedItem="{Binding Path=Song, Mode=TwoWay}"
        Visibility="{Binding Path=ListVisibility}"
        ItemContainerStyle="{StaticResource ContainerStyle}"
        HorizontalContentAlignment="Stretch"
        Width="180px" Background="#FF333333" />

我尝试为所选项目制作自定义样式。为了使选择栏伸展到ListBox的宽度,我将ItemContainerStyle的Horizo​​ntalContentAlignment属性设置为“Stretch”。问题是它没有完全拉伸,左边的一个小条仍然存在,原始(蓝色)选择条仍然可见。请参见屏幕截图:

alt text

如何让它伸展到全尺寸?或者我如何设置原始选择栏的样式?

提前致谢。

1 个答案:

答案 0 :(得分:1)

只需将ListBoxItem的Padding设置为零即可。那个蓝色条应该消失。

 <Style TargetType="{x:Type ListBoxItem}" x:Key="ContainerStyle">
      <Setter Property="Padding" Value="0"/>
      ...
 </Style>

另一个选择就是重新为ListBoxItem编写ControlTemplate,这样你就可以更好地控制它的外观。但是,在你的情况下,这可能没有必要。