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.

Advertisements

About Asad Durrani

A recent graduate Software Engineer. Interested in History, Economics and Policy

5 responses to “WPF Listbox Disable Selection

  1. steve

    Thanks for the solution. Good work.

    Marginal comment to improve your soltuin:
    The code sections have some syntax errors:
    – itemsSoutces instead of itemsSources ..
    – itemsSoutces={Binding Test}> –> “” missing
    – istBoxt instead of ListBox

  2. stephu

    thank for good work. solution 4 works perfect for me

  3. Pingback: Remove ListBox items highlighting with Mahapps controls | Just another blog

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: