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

dee*_*hao 29 wpf control-template

我想隐藏ListBox的边框,并使所选项目的背景与未选择的项目相同.

我该怎么做呢?

HCL*_*HCL 53

要隐藏边框,请使用

<ListBox BorderThickness="0"/>
Run Code Online (Sandbox Code Playgroud)

如果您不想选择,请使用ItemsControl而不是ListBox.

以下代码隐藏了ListBox周围的边框,并始终在项目上显示白色背景(如果通过ItemsSource-property 生成).

<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>
Run Code Online (Sandbox Code Playgroud)

如果使用ListViewItem实例,则必须更改其背景.

UPDATE

与此同时,我发现IMO的解决方案更加优雅:

<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>
Run Code Online (Sandbox Code Playgroud)

这应该也适用于ListBoxItem实例,并且IMO不是"解决方法".

  • 边界一有效。然而背景并没有像我预期的那样工作,所选项目的左侧仍然有一点蓝色(默认选择背景)。 (2认同)