Search code examples
c#silverlightdynamictextblock

Dynamically add textblocks with automatic wrapping


I have two columns in my Grid that contain checkboxes.

When a checkbox is checked, I need to dynamically add a textblock right below the one that is checked to display additional information for it.

How can I do this ? Obviously, adding the textblock and adjusting its position manually will be tedious or the textblock will end up being placed over other controls.

Is there a way I can add them dynamically and perform automatic wrapping of controls ?


Solution

  • It is simple as that,

    Create a canvas and divide the width by number of textbox controls you want,then Create a container it could be a grid/stackpanel or whatever you want,

    <Grid x:Name="LayoutRoot" Background="White">
    <StackPanel Grid.Row="3" Grid.Column="1" Name="split" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Width="Auto"/>
    </Grid>
    

    In code behind, to create dynamic text blocks with text wrapping, do like below,

        TextBlock b = new TextBlock();
        b.VerticalAlignment = System.Windows.VerticalAlignment.Top;
        b.FontSize = 28;
        b.TextWrapping = TextWrapping.Wrap;
        b.Width = 430;
        b.Text = "Hello World!";
        split.Children.Add(b);