WPF ListBox,如何隐藏边框并更改所选项目的背景颜色?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3351904/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
WPF ListBox, how to hide border and change selected item background color?
提问by deerchao
I'd like to hide the border of ListBox, and make background of selected item the same as unselected ones.
我想隐藏 ListBox 的边框,并使选中项的背景与未选中项的背景相同。
How do I do this?
我该怎么做呢?
回答by HCL
To hide the border, use
要隐藏边框,请使用
<ListBox BorderThickness="0"/>
If you don't want to have a selection, use an ItemsControl
instead of the ListBox
.
如果您不想进行选择,请使用ItemsControl
代替ListBox
。
The following code hides the border around the ListBox and does always show a white background on the item (if its generated through the ItemsSource
-property).
以下代码隐藏了 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>
If you use ListViewItem-instances, you must change the background there.
如果您使用 ListViewItem-instances,则必须更改那里的背景。
UPDATE
更新
In the meantime I have found a solution that is IMO much more elegant:
与此同时,我找到了一个更优雅的 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>
This should work also with ListBoxItem-instances and is IMO less "work-around".
这也应该适用于 ListBoxItem-instances,并且 IMO 较少“变通”。