Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a WPF ListBox be "read only"?

We have a scenario where we want to display a list of items and indicate which is the "current" item (with a little arrow marker or a changed background colour).

ItemsControl is no good to us, because we need the context of "SelectedItem". However, we want to move the selection programattically and not allow the user to change it.

Is there a simple way to make a ListBox non-interactive? We can fudge it by deliberately swallowing mouse and keyboard events, but am I missing some fundamental property (like setting "IsEnabled" to false without affecting its visual style) that gives us what we want?

Or ... is there another WPF control that's the best of both worlds - an ItemsControl with a SelectedItem property?

like image 790
Matt Hamilton Avatar asked Oct 02 '08 06:10

Matt Hamilton


People also ask

What is a ListBox in WPF?

ListBox is a control that provides a list of items to the user item selection. A user can select one or more items from the predefined list of items at a time. In a ListBox, multiple options are always visible to the user without any user interaction.

What is the similarities of ListView and ListBox?

A ListView is basically like a ListBox (and inherits from it), but it also has a View property. This property allows you to specify a predefined way of displaying the items. The only predefined view in the BCL (Base Class Library) is GridView , but you can easily create your own.


2 Answers

One option is to set ListBoxItem.IsEnabled to false:

<ListBox x:Name="_listBox">
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <Setter Property="IsEnabled" Value="False"/>
        </Style>
    </ListBox.ItemContainerStyle>
</ListBox>

This ensures that the items are not selectable, but they may not render how you like. To fix this, you can play around with triggers and/or templates. For example:

<ListBox x:Name="_listBox">
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <Setter Property="IsEnabled" Value="False"/>
            <Style.Triggers>
                <Trigger Property="IsEnabled" Value="False">
                    <Setter Property="Foreground" Value="Red" />
                </Trigger>
            </Style.Triggers>
        </Style>
    </ListBox.ItemContainerStyle>
</ListBox>
like image 141
Kent Boogaart Avatar answered Oct 12 '22 10:10

Kent Boogaart


I had the same issue. I resolved it by leaving the IsEnabled set to true and handling the PreviewMouseDown event of the ListBox. In the handler set e.Handled to true in the case you don't want it to be edited.

    private void lstSMTs_PreviewMouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
    {
        e.Handled = !editRights;
    }
like image 45
Jim Avatar answered Oct 12 '22 11:10

Jim