【问题标题】:HorizontalContentAlignment of SelectedItem not stretching perfectlySelectedItem 的 Horizo​​ntalContentAlignment 没有完美拉伸
【发布时间】:2010-09-30 18:40:30
【问题描述】:

我在 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”。问题是它没有完全伸展,左边的一个小条仍然存在,原来的(蓝色)选择条在那里仍然可见。看截图:

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

提前致谢。

【问题讨论】:

    标签: wpf styles


    【解决方案1】:

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

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

    另一种选择是重新编写 ListBoxItem 的 ControlTemplate,这样您就可以更好地控制它的外观。但是,是的,在您的情况下这可能不是必需的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-09
      相关资源
      最近更新 更多