WPF how to make a listbox/listview unfocusable
Asked Answered
M

2

7

I've been trying for a while to display some data in a listbox/listview that would be unfocusable (I mean not only the list, but also the items in it).

I tried with both types of list (listbox and listview), and I used their ItemTemplate and ItemContainerStyle. Everywhere I could, I set the Focusable property to false.

I don't see any other way than disabling the list, but then I have to change all its style, to make it appear not disabled.

Have I missed something? Is there a read-only type of list that I don't know about?

Thank you for your ideas :)

Malisamalison answered 21/3, 2011 at 12:18 Comment(3)
Why do you want the list to be unfocusable? If you just want to stop things being selectable, you can use ItemsControl instead.Gherardi
@DanPuzey: One purpose can be that the focus needs to stay somewhere else, rather than being "stolen" by the listbox (when, for example, the listbox is in a popup), while still having click-selectable items.Cramp
In order to be able to click/select an item, it has to be focussable. (My accepted answer in the question makes this point.) If you need to click something, it has to be able to take focus to handle the click (plus, obviously, keyboard interactions are completely broken for non-focussable controls).Gherardi
G
17

The problem you're probably seeing is that each individual item in the list is focusable. However, you can override that... Try adding this to your listbox:

  <ListBox.ItemContainerStyle>
    <Style TargetType="Control">
      <Setter Property="Focusable" Value="False" />
    </Style>
  </ListBox.ItemContainerStyle>

Note however that this makes the items unselectable (by keyboard or by mouse). You can set the selected item programmatically, but it doesn't appear to be highlighted automatically any more - so really, this behaves almost the same as an ItemsControl.

Gherardi answered 21/3, 2011 at 13:6 Comment(2)
This must be it, and programmatically setting IsSelected to true does highlight the item, at least on Windows 7 Aero.Offstage
Thank you Dan, that's exactly what I wanted. The problem with the Items control is that it's not possible to select any of the items with bindings. In my program, selecting items still get highlighted automatically, fortunately.Malisamalison
R
4

Use an ItemsControl with TextBlocks instead of a ListBox

<ItemsControl ItemsSource="{Binding MyListBoxItemsSource}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding MyDisplayName}" />
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>
Rosenstein answered 21/3, 2011 at 13:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.