【问题标题】:WPF ListBox, how to hide border and change selected item background color?WPF ListBox,如何隐藏边框并更改所选项目的背景颜色?
【发布时间】:2010-07-28 10:19:29
【问题描述】:

我想隐藏 ListBox 的边框,并使选中项的背景与未选中项的背景相同。

我该怎么做?

【问题讨论】:

    标签: wpf control-template


    【解决方案1】:

    要隐藏边框,请使用

    <ListBox BorderThickness="0"/>
    

    如果您不想进行选择,请使用 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>
    

    如果你使用 ListViewItem-instances,你必须改变那里的背景。

    更新

    与此同时,我找到了一个比 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>
    

    这也应该适用于 ListBoxItem-instances 并且是 IMO 较少的“解决方法”。

    【讨论】:

    • 边框有效。但是背景并没有像我预期的那样工作,所选项目的左侧仍然有一点蓝色(默认选择背景)。
    • 将容器的Padding设置为0。看我的例子,我已经做了相应的修改。
    • 感谢 ItemsControl 提示。我不知道这种控制。
    猜你喜欢
    • 2021-05-25
    • 1970-01-01
    • 2023-03-07
    • 2010-10-16
    • 2020-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多