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?
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.
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.
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>
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With