以编程方式创建XAML网格行

时间:2015-07-22 18:59:51

标签: c# xaml

我试图以编程方式生成数据网格。

private void WorkPackageSearchButton_Click(object sender, RoutedEventArgs e)
{
    EWP[] workPackages = SqlDataLayer.getSearchedWorkPackages(WorkPackageSearchBox.Text); 
    //declare variables
    RowDefinition RowDef;
    StackPanel StackP;
    TextBlock TextB;
    TextBlock TextC;

    for (int i = 0; i < workPackages.Length; i++)
    {
        //Define new Row to add
        RowDef = new RowDefinition();
        RowDef.Height = new GridLength(30);

        //Add row definition to Grid
        WorkPackageResults.RowDefinitions.Add(RowDef);

        //Define the control that will be added to new row
        TextB = new TextBlock();
        TextB.Text = workPackages[i].EWPStatus;
        //TextB.Width = 75;

        TextC = new TextBlock();
        TextC.Text = workPackages[i].EWPCode;
        //TextC.Width = 175;

        //create stackpanel and define which row to add the stackpanel to
        StackP = new StackPanel();
        StackP.SetValue(Grid.RowProperty, i);

        //add your control to the stackpanel
        StackP.Children.Add(TextB);
        StackP.Children.Add(TextC);
        //add the stackpanel to the grid
        WorkPackageResults.Children.Add(StackP);
    } 
}

结果是数据相互叠加:

enter image description here

如何让每次迭代循环中的每个文本块在一行中彼此相邻?

1 个答案:

答案 0 :(得分:1)

您必须将正在使用的StackPanel的方向设置为水平

StackP = new StackPanel();
StackP.Orientation = Orientation.Horizontal;

StackPanel的默认方向是垂直,因此它显示基于行的项目。

Msdn Link and Examples