AgainMe AgainMe - 3 months ago 13
C# Question

Cannot display ScrollViewer with stackpanel

I'm using a

ListBox
and I'm trying to display the scrollviewer but I need to use a stackpanel 'cause I need to align my item in horizontal mode, see the code:

<ListBox VerticalAlignment="Stretch"
Background="AliceBlue"
ScrollViewer.CanContentScroll="True"
ScrollViewer.VerticalScrollBarVisibility="Visible"
ItemsSource="{Binding EventInfo}">
<ListBox.ItemTemplate>
<DataTemplate>
<ScrollViewer CanContentScroll="True" VerticalScrollBarVisibility="Auto">
<StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock Text="Gara" FontWeight="Bold" Margin="0, 0, 50, 0"/>
<TextBlock Text="{Binding League}" />
</StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock Text="Data" FontWeight="Bold" Margin="0, 0, 50, 0"/>
<TextBlock Text="{Binding Date}" />
</StackPanel>
</StackPanel>
</StackPanel>
</ScrollViewer>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>


How you can see I put the
ScrollViewer
outside the
Stackpanel
to make it work. Unfortunately the scrollviewer appear but seems disabled, and seems not working 'cause I should able to scroll the item inside but I can't. How can I fix this?

Answer

You do not need a ScrollViewer inside your DataTemplate, as the ListBox already has a ScrollViewer set.

Also, yo should update your DataTemplate to use a Grid (it's cleaner then stacking StackPanels).

    <ListBox VerticalAlignment="Stretch" 
             Background="AliceBlue"
             ScrollViewer.CanContentScroll="True" 
             ScrollViewer.VerticalScrollBarVisibility="Auto"
             ItemsSource="{Binding EventInfo}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition/>
                        <ColumnDefinition/>
                        <ColumnDefinition/>
                        <ColumnDefinition/>
                    </Grid.ColumnDefinitions>
                    <Grid.RowDefinitions>
                        <RowDefinition/>
                        <RowDefinition/>
                    </Grid.RowDefinitions>
                    <TextBlock Text="Gara" FontWeight="Bold" Margin="0, 0, 50, 0"
                               Grid.Column="0"
                               Grid.Row="0"/>
                    <TextBlock Text="{Binding League}" 
                               Grid.Column="1"
                               Grid.Row="0"/>
                    <TextBlock Text="Data" FontWeight="Bold" Margin="0, 0, 50, 0"
                               Grid.Column="0"
                               Grid.Row="1"/>
                    <TextBlock Text="{Binding Date}"
                               Grid.Column="1"
                               Grid.Row="1"/>
                </Grid>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

Edit: ScrollBar is now visible and works. http://imgur.com/a/t2WPa

Comments