Gridview中动态创建控件的排列

时间:2012-11-30 10:25:13

标签: c# wpf xml gridview

以下是从XML文件中获取值的代码:

foreach (XmlNode node in DOC.SelectNodes("//CheckMarkObject"))
{
    FbCheckMark checkmark = new FbCheckMark();

    checkmark.Name = node.SelectSingleNode("Name").InnerText;
    checkmark.Label = node.SelectSingleNode("Label").InnerText;

    if (node.SelectSingleNode("IsChecked").InnerText == "0")
    {
        checkmark.IsChecked = false;
    }
    else
    {
        checkmark.IsChecked = true;
    }

    listCheckMarks.Add(checkmark);

}

现在在运行时创建控件的代码:

for (int i = 0; i < listCheckMarks.Count; i++)
{
if (listCheckMarks[i].checkMark.Equals(checkMark))
{

CheckBox cb = new CheckBox();
TextBlock cbtextblock = new TextBlock();
cbtextblock.Text = listCheckMarks[i].Label;
cbtextblock.Height = 27;
cbtextblock.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
cbtextblock.Margin = new Thickness(12, 20, 0, 0);
cbtextblock.VerticalAlignment = System.Windows.VerticalAlignment.Top;
cb.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
cb.VerticalAlignment = System.Windows.VerticalAlignment.Top;
cb.Margin = new Thickness(150, 21, 0, 0);
cb.Height = 50;
cb.Width = 100;
cb.Name = listCheckMarks[i].Name;




LayoutRoot.Children.Add(cbtextblock);
LayoutRoot.Children.Add(cb);

}
}

当我在我的XML文件中进行更改时,即创建两次“CheckMark”标记。结果控件覆盖前一个。我想在前一个控件下安排新控件。 请建议我,我该怎么办?像android一样使用线性布局? 谢谢

1 个答案:

答案 0 :(得分:2)

尝试将元素插入StackPanel并为其设置Orientation属性。

试试这个例子:

StackPanel container = new StackPanel();
LayoutRoot.Children.Add(container);

for (int i = 0; i < listCheckMarks.Count; i++)
{
   if (listCheckMarks[i].checkMark.Equals(checkMark))
   {

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

       CheckBox cb = new CheckBox();
       TextBlock cbtextblock = new TextBlock();
       cbtextblock.Text = listCheckMarks[i].Label;
       cbtextblock.Height = 27;
       cbtextblock.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
       cbtextblock.Margin = new Thickness(12, 20, 0, 0);
       cbtextblock.VerticalAlignment = System.Windows.VerticalAlignment.Top;
       cb.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
       cb.VerticalAlignment = System.Windows.VerticalAlignment.Top;
       cb.Margin = new Thickness(150, 21, 0, 0);
       cb.Height = 50;
       cb.Width = 100;
       cb.Name = listCheckMarks[i].Name;




      childContainer.Children.Add(cbtextblock);
      childContainer.Children.Add(cb);

      container.Children.Add(childContainer);


  }
}