How to add a grid inside a Scroll viewer programma

2019-06-16 00:53发布

问题:

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

回答1:

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. :)