C# 将文本块动态添加到网格

C# 将文本块动态添加到网格,c#,xaml,windows-runtime,windows-store-apps,winrt-xaml,C#,Xaml,Windows Runtime,Windows Store Apps,Winrt Xaml,我的网格有两行两列,我想在第一行第二列动态添加一个textblock 这是我的代码,它不会抛出异常,但不会显示任何内容 <Grid HorizontalAlignment="Left" Height="768" VerticalAlignment="Top" Width="1366"> <Grid.RowDefinitions> <RowDefinition Height="150"/> <

我的网格有两行两列,我想在第一行第二列动态添加一个textblock

这是我的代码,它不会抛出异常,但不会显示任何内容

<Grid HorizontalAlignment="Left" Height="768" VerticalAlignment="Top" Width="1366">
        <Grid.RowDefinitions>
            <RowDefinition Height="150"/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition Width="250"/>
        </Grid.ColumnDefinitions>
    </Grid>


protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            TextBlock txt = new TextBlock();
            txt.Width = 200;
            txt.Height = 100;
            txt.Foreground = new SolidColorBrush(Colors.Yellow);

            var location = await InitializeLocationServices();
            txt.Text = location;

            Grid.SetRow(txt, 0);
            Grid.SetColumn(txt, 1);

        }

受保护的异步重写无效OnNavigatedTo(NavigationEventArgs e)
{
TextBlock txt=新的TextBlock();
txt.宽度=200;
高度=100;
txt.前台=新的SolidColorBrush(Colors.Yellow);
var location=await InitializeLocationServices();
txt.Text=位置;
Grid.SetRow(txt,0);
Grid.SetColumn(txt,1);
}

您永远不会将文本块添加到网格中。您应该命名网格(例如x:name=“myGrid”)并在某个时候调用myGrid.Children.Add(txt)。

类似的,我只需要这一行就可以将其添加到我需要的行和列中?不,您需要它将其添加到可视化树中。否则-您只是创建一个文本块,而不是将其添加到任何内容中。您仍然需要设置所有属性。