代码之家  ›  专栏  ›  技术社区  ›  deerchao

WPF列表框,如何隐藏边框和改变选中项目的背景色?

  •  27
  • deerchao  · 技术社区  · 14 年前

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

    1 回复  |  直到 9 年前
        1
  •  56
  •   HCL    14 年前

    要隐藏边框,请使用

    <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>
    

    推荐文章