Approach 1 - ItemsControl Unless you need other aspects of the ListBox , you could use ItemsControl instead. It places items in the ItemsPanel and doesn't have the concept of selection. By default, ItemsControl doesn't support virtualization of its child elements.
listBox1. Items. Add("Item Code" + "\t\t" + "Item Name");
ItemsControl
Unless you need other aspects of the ListBox
, you could use ItemsControl
instead. It places items in the ItemsPanel
and doesn't have the concept of selection.
<ItemsControl ItemsSource="{Binding MyItems}" />
By default, ItemsControl
doesn't support virtualization of its child elements. If you have a lot of items, virtualization can reduce memory usage and improve performance, in which case you could use approach 2 and style the ListBox
, or add virtualisation to your ItemsControl
.
ListBox
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>
I found a very simple and straight forward solution working for me, I hope it would do for you as well
<ListBox ItemsSource="{Items}">
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="Focusable" Value="False"/>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
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.
Another option worth considering is disabling the ListBoxItems. This can be done by setting the ItemContainerStyle as shown in the following snippet.
<ListBox ItemsSource="{Binding YourCollection}">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="IsEnabled" Value="False" />
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
If you don't want the text to be grey you can specify the disabled color by adding a brush to the style's resources with the following key: {x:Static SystemColors.GrayTextBrushKey}. The other solution would be to override the ListBoxItem control template.
This will also work, if I have the need to use listbox instead of itemscontrol, but am just displaying the items which shouldn't be selectable, I use:
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="IsHitTestVisible" Value="False" />
</Style>
</ListBox.ItemContainerStyle>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With