如何在WP7上动态填充网格?

时间:2012-04-14 21:52:28

标签: c# windows-phone-7 grid

这是我在WP7中的第一个程序,所以我有一些问题。

我正在尝试使用另一种方法购买的对象列表填充网格。这是我到目前为止所做的:

public partial class MainPage : PhoneApplicationPage
{
    private List<Row> lsResult;
    private Grid myGrid = new Grid();
    private int i = 0;

    // Constructor
    public MainPage()
    {
        InitializeComponent();

        ColumnDefinition colData = new ColumnDefinition();
        ColumnDefinition colOcorrencia = new ColumnDefinition();
        ColumnDefinition colSituacao = new ColumnDefinition();
        myGrid.ColumnDefinitions.Add(colData);
        myGrid.ColumnDefinitions.Add(colOcorrencia);
        myGrid.ColumnDefinitions.Add(colSituacao);
        myGrid.ShowGridLines = true;
        SolidColorBrush myBrush = new SolidColorBrush(Colors.White);
        myGrid.Background = myBrush;
        gridResult = myGrid;

    }

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        i = 0;
        lsResult = null;
        lsResult = Rastrear.Busca(txtNumber.Text);
        foreach (Row r in lsResult)
        {
            RowDefinition rNewRow = new RowDefinition();
            myGrid.RowDefinitions.Add(rNewRow);

            TextBlock lblData = new TextBlock();
            lblData.Text = r.Data.ToString();
            lblData.HorizontalAlignment = HorizontalAlignment.Center;
            lblData.VerticalAlignment = VerticalAlignment.Center;
            Grid.SetColumnSpan(lblData, 1);
            Grid.SetRow(lblData, i);

            TextBlock lblOcorrencia = new TextBlock();
            lblOcorrencia.Text = r.Ocorrencia.ToString() ;
            Grid.SetColumnSpan(lblOcorrencia, 2);
            Grid.SetRow(lblOcorrencia, i);

            TextBlock lblSituacao = new TextBlock();
            lblSituacao.Text = r.Situacao.ToString();
            Grid.SetColumnSpan(lblSituacao, 3);
            Grid.SetRow(lblSituacao, i);
            i++;

            myGrid.Children.Add(lblData);
            myGrid.Children.Add(lblOcorrencia);
            myGrid.Children.Add(lblSituacao);   
        }
        gridResult = myGrid;

    }
}

方法Buscar()正在按原样返回列表,但是当我点击按钮时它没有做任何事情,甚至连构造函数上的paint都变为白色。

提前致谢

1 个答案:

答案 0 :(得分:1)

你在代码背后做了一些非常阴暗的东西,我以前常常看到,应该在xaml中完成。改变这个

gridResult = myGrid;

gridResult.Children.Add(myGrid);

我认为你不能像这样更改静态UI元素的引用。