Search code examples
wpfgridlabelscrollviewerstackpanel

WPF ScrollViewer not working in Grid programmatically populated


I have this situation in xaml

<StackPanel Orientation="Vertical" Margin="5" Background="AliceBlue" Height="370">
    <ScrollViewer VerticalScrollBarVisibility="Auto">
        <Grid Name="DescriptionsGrid" MinHeight="0" MaxHeight="370" ScrollViewer.CanContentScroll="True"></Grid>
    </ScrollViewer>
</StackPanel>

and I'm filling the Grid with the following

DescriptionsGrid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });
TextBlock textBlock = new TextBlock { Text = description, TextWrapping = TextWrapping.WrapWithOverflow };
Label label = new Label { Content = textBlock, Foreground = new SolidColorBrush(Colors.Blue) };
label.MouseLeftButtonDown += new MouseButtonEventHandler(LoadXML);
DescriptionsGrid.Children.Add(label);
Grid.SetRow(DescriptionsGrid.Children[DescriptionsGrid.Children.Count - 1], description_counter);
description_counter++;

I can't define rows height as the description may be long enought to wrap the text to new line.

The scrollbar does not appears and new elements go hidden down below.

Any idea?


Solution

  • Following the suggestion of @Clemens I rewrote the code, and found that the mistake was in the XML.

    To populate the grid

            foreach (HostMessages hostMessage in hostMessagesList)
            {
                Label message = new Label
                {
                    Content = new TextBlock {
                        Text = hostMessage.Description,
                        TextWrapping = TextWrapping.WrapWithOverflow
                    },
                    Foreground = new SolidColorBrush(Colors.Blue),
                    Cursor = Cursors.Hand
                };
                message.MouseLeftButtonDown += new MouseButtonEventHandler(LoadXML);
                itemsControl.Items.Add(message);
            }
    

    The XML is as follows

    <DockPanel Grid.Row="1" Margin="5" Background="AliceBlue" Height="370">
        <ScrollViewer VerticalScrollBarVisibility="Auto" Height="370">
            <ItemsControl Name="itemsControl"></ItemsControl>
        </ScrollViewer>
    </DockPanel>
    

    The mistake was assigning a MaxHeight="370" to the Grid and none to the ScrollViewer.