【问题标题】:Add a textblock to grid dynamically将文本块动态添加到网格
【发布时间】:2012-06-10 13:02:29
【问题描述】:

我的网格有 2 行 2 列,我想在第一行第二列动态添加一个文本块。

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

<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);

        }

【问题讨论】:

标签: c# xaml windows-runtime windows-store-apps winrt-xaml


【解决方案1】:

您永远不会将 TextBlock 添加到网格中。您应该命名您的 Grid(例如 x:Name="myGrid")并在某个时候调用 myGrid.Children.Add(txt)。

【讨论】:

  • 我只需要那行添加到我需要的行和列吗?
  • 不,您需要将其添加到可视化树中。否则 - 你只是创建一个 TextBlock 而没有将它添加到任何东西。你仍然需要像你一样设置所有的属性。
猜你喜欢
  • 2015-12-07
  • 1970-01-01
  • 1970-01-01
  • 2018-04-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多