make Listbox items in WPF not selectable

If you don't need selection, use an ItemsControl rather than a ListBox


Please use this inside your listbox. I found this very elegant solution

<ListBox ItemsSource="{Binding YourCollection}">
    <ListBox.ItemContainerStyle>
       <Style TargetType="{x:Type ListBoxItem}">
           <Setter Property="Focusable" Value="False"/>
        </Style>
    </ListBox.ItemContainerStyle>
</ListBox>

Add Focusable property as false in ListBoxItem style:

<Style x:Key="{x:Type ListBoxItem}" TargetType="{x:Type ListBoxItem}">
  <!-- Possibly other setters -->
  <Setter Property="Focusable" Value="False" />
</Style>

If you dont want them selectable then you probably dont want a listview. But if this is what you really need then you can do it with a style:

<Page
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <Page.Resources>


<Style x:Key="{x:Type ListBoxItem}" TargetType="{x:Type ListBoxItem}">
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="{x:Type ListBoxItem}">
        <Border 
          Name="Border"
          Padding="2"
          SnapsToDevicePixels="true">
          <ContentPresenter />
        </Border>
        <ControlTemplate.Triggers>
          <Trigger Property="IsSelected" Value="true">
            <Setter TargetName="Border" Property="Background" Value="#DDDDDD"/>
          </Trigger>
          <Trigger Property="IsEnabled" Value="false">
            <Setter Property="Foreground" Value="#888888"/>
          </Trigger>
        </ControlTemplate.Triggers>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>

  </Page.Resources>
  <Grid>  
    <ListBox>
      <ListBoxItem>One</ListBoxItem>
      <ListBoxItem>Two</ListBoxItem>
      <ListBoxItem>Three</ListBoxItem>
    </ListBox>
  </Grid>
</Page>

Look at the IsSelected Trigger. You can make the border a different colour so it is not "Ugly" or set it to transparent and it will not be visible when selected.

Hope this helps.

Tags:

Wpf

Listbox