Search code examples
c#wpfxamllistboxexpander

displaying images in a list box so the image resizes based on parent container


I have an expander with a list box in it that displays image thumbnails. I want the images to be sized according to the size of the listbox and the list box to be sized based on the width of the expander. When I expand the expander I want the list box and the images to resize also. Does anyone know how I can accomplish this?

   <Expander
            Style="{DynamicResource ExpanderStyle}"
            Name="pictureExpander"
            IsExpanded="True"                
            ExpandDirection="Left"
            Collapsed="pictureExpander_Collapsed"
            Expanded="pictureExpander_Expanded"
            Grid.Column="4">
            <ListBox 
                Name="photoList" 
                ItemsSource="{Binding Source={StaticResource PhotoBin}}"
                IsSynchronizedWithCurrentItem="True"
                HorizontalAlignment="Stretch"
                ScrollViewer.CanContentScroll="False">
                <ListBox.ItemContainerStyle>
                    <Style TargetType="{x:Type ListBoxItem}">
                        <Style.Resources>
                            <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Yellow" />
                        </Style.Resources>
                        <Style.Triggers>
                            <Trigger Property="IsSelected" Value="True">
                                <Setter Property="BorderBrush" Value="Black"/>
                                <Setter Property="BorderThickness" Value="5"/>
                            </Trigger>
                        </Style.Triggers>
                    </Style>
                </ListBox.ItemContainerStyle>
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <Image 
                            Source="{Binding FileLocation}"
                            Margin="0,5"
                            HorizontalAlignment="Stretch"
                            MouseLeftButtonDown="DragImage" />
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>
        </Expander>

Solution

  • by using the "Stretch" Property on your image:

    <Image 
         Source="{Binding FileLocation}"
         Margin="0,5"
         MouseLeftButtonDown="DragImage"
         Stretch="Uniform"
         StretchDirection="Both"/>
    

    you can play with the values to get the effect you want:

    http://msdn.microsoft.com/en-en/library/system.windows.controls.image.stretch.aspx

    http://msdn.microsoft.com/en-en/library/system.windows.controls.image.stretchdirection.aspx

    http://msdn.microsoft.com/en-us/library/system.windows.media.stretch.aspx

    http://msdn.microsoft.com/en-us/library/system.windows.controls.stretchdirection.aspx