组动态创建的对象

时间:2013-12-30 09:14:01

标签: c# dynamic

目前我点击“添加标题”按钮,它将动态创建这些对象行。

这是我使用过的C#代码:

private void btnAddTitle_Click(object sender, RoutedEventArgs e)
{

        CurrentSortItem++;
        SortItems.Add(CurrentSortItem);

        StackPanel sp = new StackPanel() { Orientation = Orientation.Horizontal };

        ComboBox y = new ComboBox();
        y.Name = "Combo" + CurrentSortItem;
        y.SelectedItem = CurrentSortItem;
        y.Height = 25;
        y.Width = 45;
        y.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
        y.Margin = new Thickness(20, 15, 0, 0);

        foreach (int item in SortItems)
        {
            y.Items.Add(item);
        }

        TextBox x = new TextBox();
        x.Name = "Title" + CurrentSortItem;
        x.Text = "Title...";
        x.FontWeight = FontWeights.Bold;
        x.FontStyle = FontStyles.Italic;
        x.TextWrapping = TextWrapping.Wrap;
        x.Height = 25;
        x.Width = 200;
        x.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
        x.Margin = new Thickness(12, 15, 0, 0);

        sp.Children.Add(y);
        sp.Children.Add(x);

        spStandard.Children.Add(sp);

}

代码中间的Foreach循环计算我点击按钮的次数,然后在组合框中将显示有多少个标题,然后您可以更改该标题的位置。

问题

如何对标题对象(ComboBox& Textbox)进行分组,这样当我更改标题的位置时,它们会移动到该位置?

修改

我想我知道我需要更改这一行并将其变成GroupBox?

StackPanel sp = new StackPanel() { Orientation = Orientation.Horizontal };

更改为:

GroupBox sp = new GroupBox() { Orientation = Orientation.Horizontal };

但是Orientation但是不起作用......

1 个答案:

答案 0 :(得分:0)

尝试将StackPanel放在新的GroupBox中,如下所示

private void btnAddTitle_Click(object sender, RoutedEventArgs e)
{

    CurrentSortItem++;
    SortItems.Add(CurrentSortItem);

    GroupBox gb = new GroupBox();
    StackPanel sp = new StackPanel() { Orientation = Orientation.Horizontal };

    ....
    gb.Content = sp;

    spStandard.Children.Add(gb);

}