How to disable selection in a ListBox?
views:
1392answers:
4There ain't ListBox.SelectionMode="None", is there another way to disable selection in a listbox?
Unless you need other aspects of the ListBox, you could just use ItemsControl
. It'll just place items in the ItemsPanel and won't allow selection (or virtualization, IIRC.)
<ItemsControl ItemsSource="{Binding MyItems}" />
Alternatively, just style the ListBox such that the selection is not visible.
<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>
You could switch to using an ItemsControl
instead of a ListBox
. An ItemsControl
has no concept of selection, so there's nothing to turn off.
Note: This solution does not disable selection by keyboard navigation or right clicking (ie. arrow keys followed by space key)
All previous answers either remove the ability select completly (no switching in runtime) or simply remove the visual effect, but not the selection.
But what if you want to be able to select and show selection by code, but not by user input? May be you want to "freeze" the user's selection while not disabling the whole Listbox?
The solution is to wrap the whole ItemsContentTemplate into a Button that has no visual chrome. The size of the button must be equal to the size of the Item, so it's completely covered. Now use the button's IsEnabled-Property:
Enable the button to "freeze" the item's Selection-state. This works because the enabled button eats all mouse events before they bubble up to the ListboxItem-Eventhandler. Your ItemsDataTemplate will still receive MouseEvents because it's part of the buttons content.
Disable the button to enable changing the selection by clicking.
<Style x:Key="LedCT" TargetType="{x:Type ListBoxItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBoxItem}">
<Button IsEnabled="{Binding IsSelectable, Converter={StaticResource BoolOppositeConverter}}" Template="{DynamicResource InvisibleButton}">
<ContentPresenter />
</Button>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<ControlTemplate x:Key="InvisibleButton" TargetType="{x:Type Button}">
<ContentPresenter/>
</ControlTemplate>
dartrax