在textBlock中动态显示数据

时间:2013-12-02 14:45:19

标签: c# windows-phone-7 textblock

我只想动态显示数据,所以我使用了C#代码

TextBlock[] Cp = new TextBlock[ContactPersons.Count];
                int i=0;
                foreach(var item in ContactPersons)
                {
                    Cp[i] = new TextBlock();
                    Cp[i].Margin = new Thickness(0,y_coordinateStart ,0,0);
                    Cp[i].Foreground = new SolidColorBrush(Colors.Green);
                    Cp[i].Visibility = Visibility.Visible;
                    Cp[i].Height = 30;
                    Cp[i].Width = 300;
                    y_coordinateStart += 35;
                    Cp[i].Text = item.firsName;
                    i++;
                }

但我的页面中没有任何内容。

可能是什么问题?

1 个答案:

答案 0 :(得分:4)

您需要以某种方式将它们添加到可视树中......例如

在您的XAML中:

<Window x:Class="MyClass"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow"
        Width="525"
        Height="350">
   <StackPanel x:Name="MainPanel" />
</Window>

在您的代码中:

            foreach(var item in ContactPersons)
            {
                TextBlock tb = new TextBlock();
                tb.Margin = new Thickness(0,y_coordinateStart ,0,0);
                tb.Foreground = new SolidColorBrush(Colors.Green);
                tb.Visibility = Visibility.Visible;
                tb.Height = 30;
                tb.Width = 300;
                y_coordinateStart += 35;
                tb.Text = item.firsName;
                MainPanel.Children.Add(tb);
            }