Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind to a listbox, but only show the selected element?

Tags:

wpf

I have a collection of objects which I bind to a ListBox, but I actually only want to display the selected element, and not the entire collection. What's the best way to go about this? Use a different control?

I think I can do a Visibility ValueConverter which checks the IsSelected attribute -- and if not selected collapses... but I'm still interested in other ideas.

like image 333
patrick Avatar asked Dec 04 '22 22:12

patrick


2 Answers

Since the entire purpose of a ListBox is to display multiple items and provide the user with a way to select them, yes, I'd use a different control.

Or you could do this, which is getting into the territory of stupid:

<ListBox.ItemContainerStyle>
   <Style TargetType="ListBoxItem">
      <Style.Triggers>
         <Trigger Property="IsSelected" Value="false">
            <Setter Property="Visibility" Value="Collapsed"/>
         </Trigger>
      </Style.Triggers>
   </Style>
</ListBox.ItemContainerStyle>
like image 63
Robert Rossney Avatar answered Dec 07 '22 12:12

Robert Rossney


While I agree with Anders' answer, there is a way to show only the selected item in an ListBox, if, for some reason beyond my imagination, that's really what you want to do:

<ListBox>
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <Style.Triggers>
                <Trigger Property="IsSelected" Value="False">
                    <Setter Property="Visibility" Value="Collapsed" />
                </Trigger>
            </Style.Triggers>
        </Style>
    </ListBox.ItemContainerStyle>
</ListBox>
like image 36
svick Avatar answered Dec 07 '22 11:12

svick