pete757
pete757

Reputation: 329

Scale images in listview to fit

I'm trying to make a listview where each item is an image. I want the listview to display the items horizontally. If the view box items won't fit horizontally in the window I want a horizontal scroll bar. If the list items won't fit vertically within the window I want the images to scale down so they fit. Instead of the images scaling to fit I seem to be getting a vertical scrollbar on the listview.

At the moment when the window is resized vertically it causes a vertical scrollbar to appear on the listview. I've tried various options around setting the image height to the height of the ancestor listview but I can't make it work correctly. How do I achieve my desired behaviour?

<Window x:Class="ViewBoxExample.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:ViewBoxExample"
        mc:Ignorable="d"
        d:DataContext="{d:DesignInstance Type=local:MainWindow}"
        Title="Viewbox Test"
        Height="400" Width="600">
    <Window.Resources>
        <DataTemplate x:Key="ItemTemplate" >
                <Border BorderBrush="Black" BorderThickness="2" >
                    <Image Margin="2" Source="image.png" />
                </Border>
        </DataTemplate>
    </Window.Resources>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="Auto"/>
       </Grid.RowDefinitions>
        <ListView VerticalAlignment="Stretch"
                  ItemTemplate="{StaticResource ItemTemplate}"
                  ItemsSource="{Binding Items}">
            <ListView.ItemsPanel>
                <ItemsPanelTemplate>
                    <StackPanel Orientation="Horizontal">
                    </StackPanel>
                </ItemsPanelTemplate>
            </ListView.ItemsPanel>
        </ListView>
        <Grid Grid.Row="1" Height="100">
            <!--placeholder for more content-->
        </Grid>
    </Grid>
</Window>

Upvotes: 0

Views: 1746

Answers (1)

Clemens
Clemens

Reputation: 128013

Disable the vertical ScrollBar to make the ListView scale its items vertically:

<ListView ItemsSource="{Binding Items}"
          ItemTemplate="{StaticResource ItemTemplate}"
          ScrollViewer.VerticalScrollBarVisibility="Disabled">
    <ListView.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel Orientation="Horizontal" />
        </ItemsPanelTemplate>
    </ListView.ItemsPanel>
</ListView>

This works as well with the more light-weight ListBox.

Upvotes: 3

Related Questions