How to stop user from selecting items in a listbox without disabling it

血红的双手。 提交于 2019-12-07 22:53:38

问题


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.



来源:https://stackoverflow.com/questions/20957029/how-to-stop-user-from-selecting-items-in-a-listbox-without-disabling-it

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!