Goran
Goran

Reputation: 6518

ListBox inside a ListBoxItem template

I have a ListBox with the following ItemTemplate:

<DataTemplate>
  <StackPanel>
    <TextBlock .... />
    <ListBox .... />
  </StackPanel>
</DataTemplate>

I would like to forbid the user to Select an item in a child ListBox, and that when user clicks on the child ListBox, a parent ListBox SelectedItem should be set respectively.

What I have tried is to set IsHitTestVisible of the child ListBox to false, and that prevents the user to select an item on it, but the problem is that if I click on the child ListBox, the mouse click is not passed to parent ListBoxItem, so it never gets selected.

So to summarize, I need:

Upvotes: 1

Views: 1346

Answers (1)

Michael
Michael

Reputation: 436

You could replace the inner ListBox with an ItemsControl. Based on your question, it sounds like you just need to display a collection, and prevent the user from interacting with it. A simple ItemsControl is well suited for that. The ItemsControl does not support selection, so the click will get propagated up to your main ListBox.

EDIT

Based on your comment, I'd recommend trying one of two options. First, you could set IsHitTestVisible to false on the list box items, as in the following example

<!-- XAML for the inner list box -->
<ListBox>
    <ListBox.Resources>
       <Style TargetType="{x:Type ListBoxItem}">
          <Setter Property="IsHitTestVisible" Value="False" />
       </Style>
    </ListBox.Resources>
</ListBox>

This will cause the click event to propagate up to your main list box, while still being able to use a list box.

Second, maybe it would be easier to just create two separate list boxes? Again, you haven't fully explained why this is required, but trying to load up one control with different modes of functionality sometimes overcomplicates things. Having two controls, and showing only one at a time based on some condition, can be an easy way to simplify the XAML.

Upvotes: 1

Related Questions