views:

388

answers:

2

I have a listbox that uses a datatemplate. What I need is a way after the item is selected I want to shrink the listbox itself, not the listitem inside. I have tried the eventtrigger on the selector.selected and unselected but it doesn't fire. I also put a datatrigger on the datatemplate but I cannot access the listbox from here. Any Ideas?

+1  A: 

This is a slightly indirect solution, but... you can handle this by putting a DataTrigger on the ListBox itself, and binding to the SelectedItems.Count. You will need to have the ListBox default to its "smaller" appearance. Then the trigger will check if SelectedItems.Count is 0, and if so it has to make the ListBox larger. In the following example, I'm setting the ListBox.Background for simplicity, but you should be able to adapt it to operate on the LayoutTransform or RenderTransform or Width/Height or whatever you're using to "shrink" the ListBox:

<ListBox.Style>
  <Style TargetType="ListBox">
    <Style.Triggers>
      <DataTrigger Binding="{Binding SelectedItems.Count, RelativeSource={RelativeSource Self}}" Value="0">
        <Setter Property="Background" Value="Orange" />
      </DataTrigger>
    </Style.Triggers>
  </Style>
</ListBox.Style>

Obviously this will shrink (or, in my simplified example, turn white) the entire ListBox when anything is selected. To get the selected ListBoxItem to remain full sized, use the ListBox.ItemContainerStyle. In this, you can trigger on IsSelected, and apply a suitable setter to reverse the "shrinking" transformation -- e.g. apply a negative Margin, or the reverse ScaleTransform. (A normal Trigger will do for this.)

itowlson
A: 

First of all, the correct event to hook to is SelectionChanged not Selected, secondly, you can use a Storyboard at the window level:

The Storyboard:

<Storyboard x:Key="Storyboard1">
    <DoubleAnimationUsingKeyFrames 
        BeginTime="00:00:00" 
        Storyboard.TargetName="grid" 
        Storyboard.TargetProperty="(FrameworkElement.Height)">
        <SplineDoubleKeyFrame KeyTime="00:00:00.5000000" Value="0"/>
    </DoubleAnimationUsingKeyFrames>
</Storyboard>

The window trigger:

<Window.Triggers>
    <EventTrigger RoutedEvent="Selector.SelectionChanged" SourceName="listBox">
        <BeginStoryboard Storyboard="{StaticResource Storyboard1}"/>
    </EventTrigger>
</Window.Triggers>

And the ListBox (with some decorations for effect):

<Border 
    BorderThickness="2" 
    CornerRadius="3" 
    BorderBrush="#FF000000" 
    Padding="3" 
    VerticalAlignment="Top">
    <Grid Height="200" x:Name="grid">
        <ListBox x:Name="listBox" Height="200">
            <ListBoxItem Content="ListBoxItem"/>
            <ListBoxItem Content="ListBoxItem"/>
            <ListBoxItem Content="ListBoxItem"/>
            <ListBoxItem Content="ListBoxItem"/>
        </ListBox>
    </Grid>
</Border>
Aviad P.