WPF Listbox wont scroll Vertical

2019-07-15 09:50发布

问题:

Within a Groupbox I have a Listbox, ListboxItems are defined in the XAML as well. The Listbox is defined:

<ListBox Name="lvAvoidCountry" Margin="5,5,5,5"  
    Background="Transparent" 
    ScrollViewer.VerticalScrollBarVisibility="Visible"
    ScrollViewer.HorizontalScrollBarVisibility="Disabled" >

Items are defined like this:

<ListViewItem >
  <CheckBox Name="chkAlbanien" Tag="55">
    <StackPanel Orientation="Horizontal">
      <Image Source="images/flag_albania.png" Height="30"></Image>
      <TextBlock Text="Albanien" Margin="5,0,0,0"></TextBlock>
    </StackPanel>
  </CheckBox>
</ListViewItem>

If I remove the Scrollviewer Settings I get horizontal scrolling and the Items are well formatted - correct width. If I use the scrollviewer settings the items get cut off so that all items are placed on the listbox. (eg. the flag is shown, the checkbox is shown but the text is just "Alba").

Thanks for any hints!

回答1:

As the name implies, ScrollViewer.HorizontalScrollBarVisibility="Disabled" disables horizontal scrolling. If you do that, but your ListBoxItems are too long, they'll get cut off. The StackPanel won't grow or shrink to fit into the ListBox, and it won't "wrap" your items to fit into the ListBox if it's too narrow, even if you add TextWrapping to the TextBlock. It's very stubborn. I think your main problem is that StackPanel.

Instead of a StackPanel, try using a Grid with 2 columns defined like so:

<ListViewItem >
  <CheckBox Name="chkAlbanien" Tag="55">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <Image Grid.Column="0" Source="images/flag_albania.png" Height="30"/>
        <TextBlock Grid.Column="1"
                   TextWrapping="Wrap"
                   Text="Albanien" Margin="5,0,0,0"/>
    </Grid>
  </CheckBox>
</ListViewItem>

Auto will "shrinkwrap" the image columns, and * will give the text all remaining space. Then add TextWrapping to your textblock in case it's still too long.

Edited: added more complete code example and changed my answer slightly.



回答2:

if you want vertical scrolling in a listbox then don't put it in a stackpanel,instead use a grid.