3

There is something i need to do, list something in WPF but i don't want the users to click on the list, the list box does not have a property to disable selection. You can disable the control, but that's not what i need, because it messes with the styles and makes the text difficult to read. I mean there is something like:

<ListBox IsEnabled="{Binding IsValid}" ...> ... </ListBox>

I wonder if there is something like:

<ListBox Selection="Disabled" ...> ... </ListBox>

Or if there exists an alternative to listing items different to a list box

The question is, is there a way to list content in WPF and that the users can't select those items??

Javier Cadiz
  • 12,326
  • 11
  • 55
  • 76
aledustet
  • 1,003
  • 2
  • 14
  • 39
  • 1
    You may use an [`ItemsControl`](http://msdn.microsoft.com/en-us/library/system.windows.controls.itemscontrol.aspx). – Clemens Jan 06 '14 at 18:48
  • 1
    If you have to use a `ListBox` for whatever reason(like showing over state but not let them select it), just set `SelectedIndex` to -1 in the SelectionChanged event. `lb.SelectionChanged += (sender, args) => lb.SelectedIndex = -1;` – Viv Jan 06 '14 at 18:53
  • @viv I had tried to do that in the set of the SelectedIndex and it does not work but in SelectionChanged event it does work. – paparazzo Jan 06 '14 at 19:01

2 Answers2

4

Use ItemsControl in place of ListBox. ItemsControl is a lookless control.

But virtualization is not supported (by default) for ItemsControl, you have to do some changes to support virtualization(in case you want).

Refer to this if you want to support virtualization here - Virtualizing an ItemsControl.


Either you can set IsHitTestVisible to false on ListBoxItem which disallows any mouse inputs on it. You can set it using ItemContainerStyle.

    <ListBox>
        <ListBox.ItemContainerStyle>
            <Style TargetType="ListBoxItem">
                <Setter Property="IsHitTestVisible" Value="False"/>
            </Style>
        </ListBox.ItemContainerStyle>
    </ListBox>
Community
  • 1
  • 1
Rohit Vats
  • 79,502
  • 12
  • 161
  • 185
0

Using the MVVM pattern, your ViewModel should be keeping track of SelectedItems. You can bind this to the ListBox.SelectedItems property so that it stays in sync.

You can have the ViewModel control the validation logic for selecting items. ListBox.SelectionChanged event can be hooked into and with a property on the model, like CanSelect you can selectively select items.

Erik
  • 12,730
  • 5
  • 36
  • 42