1

Project build target: Windows 10 Fall Creators Update (introduced v10.0.16299.0).

I am dynamically adding TextBlock-s:

    TextBlock headName = new TextBlock();
    headName.Text = h3.OuterHtml;
    headName.IsTextSelectionEnabled = true;
    headName.Style = (Style)Application.Current.Resources["TitleTextBlockStyle"];

    GridView.Children.Add(headName);
//...
        foreach (HtmlNode p in ps)
        {
            TextBlock pTag = new TextBlock();
            pTag.Text = p.InnerText;
            pTag.IsTextSelectionEnabled = true;
            pTag.FontSize = 16;
            pTag.TextWrapping = TextWrapping.Wrap;

            GridView.Children.Add(pTag);
        }

Into xaml Grid:

<Grid   x:Name="GridView"
        Loaded="GridView_Loaded"
        Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
</Grid>

But text is stacked on each other. Stacked TextBlock-s Any ideas?

tprieboj
  • 1,680
  • 6
  • 31
  • 54

1 Answers1

2

This is normal behavior for a <Grid>

note: your Grid is not the GridView as described here: https://learn.microsoft.com/en-us/uwp/api/Windows.UI.Xaml.Controls.GridView

If you use a StackPanel the items get stacked... well... in the other form that is.

Eg:

<StackPanel x:Name="Stack"
    Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
</StackPanel>

With code:

foreach (HtmlNode p in ps)
{
    //...
    Stack.Children.Add(pTag);
}

Having said that, I would advise you to look at binding, MVVM and xaml.

Your problem could be solved a more elegant way.

You also can use Templates, with them you can keep your UI fully XAML based, without the need to add children in code behind.

See: https://learn.microsoft.com/en-us/windows/uwp/controls-and-patterns/control-templates

Aditional info:

Databind from XAML to code behind

https://social.msdn.microsoft.com/Forums/en-US/238bed43-e75a-472f-91c3-e16418b7948b/uwp-xaml-mvvm-binding-listbox-to-viewmodel-data?forum=wpdevelop

Stefan
  • 17,448
  • 11
  • 60
  • 79