How to stop user from selecting items in a listbox

2019-05-29 00:08发布

问题:

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??

回答1:

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>


回答2:

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.