WPF ListBox,如何隐藏边框并更改选定项目的背景颜色?

33
我想隐藏ListBox的边框,并使所选项目的背景与未选项目相同。
我该怎么做?
1个回答

58

要隐藏边框,请使用

<ListBox BorderThickness="0"/>

如果您不想要选择功能,请使用ItemsControl而不是ListBox

以下代码可以隐藏ListBox周围的边框,并始终在项上显示白色背景(如果是通过ItemsSource属性生成的话)。

<ListBox BorderThickness="0" HorizontalContentAlignment="Stretch">
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
              <Setter Property="Padding" Value="0"/>
        </Style>
    </ListBox.ItemContainerStyle>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Grid Background="White">
                <ContentPresenter Content="{Binding}"/>
            </Grid>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

如果您使用ListViewItem实例,则必须在那里更改背景。

更新

与此同时,我已经找到了一种解决方案,它在我看来更加优雅:

<ListBox BorderThickness="0" HorizontalContentAlignment="Stretch"  >
    <ListBox.Resources>
        <Style TargetType="ListBoxItem">
            <Style.Resources>
                <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Transparent"/>
                <SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="Transparent"/>
                <SolidColorBrush x:Key="{x:Static SystemColors.HighlightTextBrushKey}" Color="Black"/>
            </Style.Resources>
        </Style>
    </ListBox.Resources>                
</ListBox>

这也适用于ListBoxItem实例,并且我认为这种方法更少"折中".


2
边框是有效的。然而,背景并不像我预期的那样有效,选定项左侧仍有一点蓝色(默认选择背景)。 - deerchao
将容器的填充设置为0。请参考我的示例,我已经相应地进行了更改。 - HCL
1
感谢您提供的ItemsControl提示。我之前不知道这个控件。 - Ignacio Soler Garcia

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接