WPF Listbox Disable Selection

While developing in WPF

I Browsed through the web to get the solution to the problem I was facing today, the problem was that I wanted to disable the selection of WPF Listbox,

I found multiple solutions to that

1. One solution was to use ItemsControl instead of Listbox but the customization of look and feel stopped me to use that solution.

2. The other solution recommended to update background of the ListBoxItem using trigger, I thought this solution would work but it didn’t worked for me. But I still it can work for many other facing the same problem.

This is how I did it


<ListBox.ItemContainerStyle>

<Style TargetType="{x:Type ListBoxItem}">

<Setter Property="Background" Value="Green"/>

<Style.Triggers>

<Trigger Property="IsSelected" Value="True">

<Setter Property="Background" Value="transparent"/>

</Trigger>

</Style.Triggers>

</Style>

</ListBox.ItemContainerStyle>

3. The third solution was to update the selection brush color so that it feels selection is disabled. This is how we achieve it


<ListBox itemsSources="{Binding Test}">

<ListBox.ItemContainerStyle>

<Style TargetType="{x:Type ListBoxItem}">

<Style.Resources>

<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="transparent" />

<SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}"  Color="transparent" />

</Style.Resources>

</listBox.ItemContainerStyle>

</ListBox>

4. The final solution that I chose for my self was to set the IsFocusable property of Listbox item to false like this


<ListBox itemsSources="{Binding Test}">

<ListBox.ItemContainerStyle>

<Style TargetType="{x:Type ListBoxItem}">

<Setter Property="Focusable" Value="False"/>

</listBox.ItemContainerStyle>

</ListBox>

This wraps up the solutions in my knowledge.