我如何禁用列表框的选择?
当前回答
对我来说,最好的解决办法是:
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="Focusable" Value="True"/>
<Setter Property="IsHitTestVisible" Value="False" />
</Style>
</ListBox.ItemContainerStyle>
其他回答
IsEnabled = false
你可以在你的列表框上面放置一个文本块,它不会改变你的应用程序的外观,也不允许选择任何项目。
方法1 -项目控制
除非你需要ListBox的其他方面,你可以使用ItemsControl代替。它将项目放在ItemsPanel中,没有选择的概念。
<ItemsControl ItemsSource="{Binding MyItems}" />
默认情况下,ItemsControl不支持其子元素的虚拟化。如果你有很多项,虚拟化可以减少内存使用和提高性能,在这种情况下,你可以使用方法2和样式ListBox,或添加虚拟化到你的ItemsControl。
方法2 -样式化列表框
或者,只是样式ListBox这样选择是不可见的。
<ListBox.Resources>
<Style TargetType="ListBoxItem">
<Style.Resources>
<!-- SelectedItem with focus -->
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}"
Color="Transparent" />
<!-- SelectedItem without focus -->
<SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}"
Color="Transparent" />
<!-- SelectedItem text foreground -->
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightTextBrushKey}"
Color="Black" />
</Style.Resources>
<Setter Property="FocusVisualStyle" Value="{x:Null}" />
</Style>
</ListBox.Resources>
我提出另一种解决办法。简单地重新模板ListBoxItem只不过是一个ContentPresenter,就像这样…
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBoxItem}">
<ContentPresenter />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
我采用这种方法的原因如下:
In my case, I don't want to disable user interaction with the contents of my ListBoxItems so the solution to set IsEnabled won't work for me. The other solution that attempts to re-style the ListBoxItem by overriding the color-related properties only works for those instances where you're sure the template uses those properties. That's fine for default styles, but breaks with custom styles. The solutions that use an ItemsControl breaks too many other things as the ItemsControl has a completely different look than a standard ListBox and doesn't support virtualization, meaning you have to re-template the ItemsPanel anyway.
上述内容不会改变ListBox的默认外观,不会禁用ListBox数据模板中的项,默认支持虚拟化,并且独立于应用程序中可能使用或不使用的任何样式。这就是KISS原则。
你可以切换到使用ItemsControl而不是ListBox。ItemsControl没有选择的概念,所以没有什么可以关闭的。
推荐文章
- AppSettings从.config文件中获取值
- 如何检查IEnumerable是否为空或空?
- 没有ListBox。SelectionMode="None",是否有其他方法禁用列表框中的选择?
- 在c#代码中设置WPF文本框的背景颜色
- 如何在iis7应用程序池中设置。net Framework 4.5版本
- 如何分裂()一个分隔字符串到一个列表<字符串>
- 如何指定最小值,但没有使用范围数据注释属性的最大小数?
- 如何在PowerShell中获得本地主机名?
- 为什么在Java和。net中不能修改字符串?
- 禁用Visual Studio 2015额外调试选项
- 'throw'和'throw new Exception()'的区别
- c# int到字节[]
- 如何跟踪log4net问题
- 将WPF组合框绑定到自定义列表
- foreach vs somlist . foreach (){}