How to add a grid inside a Scroll viewer programmatically

user330612 picture user330612 · Nov 16, 2011 · Viewed 12.1k times · Source

My XAML looks like this

<navigation:Page x:Class="SilverlightApplication1.Home">

    <Grid x:Name="LayoutRoot">
    <!--
    <ScrollViewer>
        <Grid>
            <TextBlock Text="myTextBlock" />
        </Grid>
    </ScrollViewer>
    -->
</Grid>

I want to programmatically do the commented part above via code behind.

And my code behind looks like this

public partial class Home : Page
{
    public Home()
    {
        InitializeComponent();

        ScrollViewer sv = new ScrollViewer();
        Grid grid = new Grid();
        TextBlock block = new TextBlock();

        block.Text = "My Text block";
        grid.Children.Add(block);

        sv.ScrollIntoView(grid);
        LayoutRoot.Children.Add(sv);

    }

This doesnt work, since it only shows the scroll viewer but the text block is hidden.

What is that I'm missing?

Is there a way to add children to the "ScrollViewer" control programmatically w/o using the extension method "ScrollIntoView" available in the silverlight toolkit? i didnt find a property called "Children" for ScrollViewer element

Thanks for the help

Answer

Justin XL picture Justin XL · Nov 16, 2011

You didn't specify the ScrollViewer's content, just do this before the last line. Also you can remove the ScrollIntoView method.

sv.Content = grid;

Hope it helps. :)