Search code examples
wpfimagelistboxscalingitemscontrol

Scaling images in a WPF ListBox


I've started developing my code using the example from SO WPF: arranging collection items in a grid. Now, to gain cell selection capability, I renamed each ItemsControl to ListBox, because a ListBox is-a ItemsControl (XAMl somewhat simplified):

<ListBox  HorizontalContentAlignment="Stretch"  VerticalContentAlignment="Stretch" ItemsSource="{Binding YourItems}"> 
<ListBox.ItemsPanel> 
    <ItemsPanelTemplate> 
        <Grid/> 
    </ItemsPanelTemplate> 
</ListBox.ItemsPanel> 
<ListBox.ItemContainerStyle> 
    <Style> 
        <Setter Property="Grid.Column" Value="{Binding X}"/> 
        <Setter Property="Grid.Row" Value="{Binding Y}"/> 
    </Style> 
</ListBox.ItemContainerStyle> 
       <ListBox.ItemTemplate>
            <DataTemplate>
                <Image RenderOptions.BitmapScalingMode="LowQuality" Source="{Binding  ...ImageSource, Mode=OneWay}">
                </Image>
            </DataTemplate>
        </ListBox.ItemTemplate>

The grid is filled with glyph run test imaged, based on the code here.

Surprisingly it worked - kind of. Selection works. However, in the case of the ItemsControl, there was no scroll bar. Everything scaled nicely. When I made the window smaller, the grid cells shrunk and so did the images. When I made the window larger, everything scaled up.

Now, with the ListBox that's not the case. The images size stays fixed. If the window isn't large enough, there's an horizontal scroll bar and when the window isn't large enough, some of the images are hidden and the user needs to scroll to the right.

So, my question is: If a ListBox is-an ItemControl, why don't my images scale the same? What should I do to correct it?


Solution

  • This is because ListBox and ItemsControl use different styles. You might easily apply the ItemControl's default style to your ListBox:

    <ListBox Style="{StaticResource ResourceKey={x:Type ItemsControl}}">