使用UWP中的位置动态添加ComboBox

时间:2017-03-27 10:06:44

标签: c# combobox uwp

我是这项技术的新手。问题是我无法动态地向ComboBox添加位置。我有一个Button,它在click事件上添加了一个comboBox。 Button应该在第一个下面添加ComboBox。我写了这段代码:

  private void button1_Click(object sender, RoutedEventArgs e)
    {
        ComboBox combobox = new ComboBox();
        combobox.ItemsSource = credithr_list;
        // Location of comboBox should add here
        grid2.Children.Add(combobox);
    }

我应该如何修改它,这样我才能达到理想的效果。

2 个答案:

答案 0 :(得分:1)

我的解决方案基于UWP XAML中的RelativePanel控件。

你的组合框将存在于相对面板中并使用其附加属性,例如:下方,上方等...您可以获得所需的结果。

这是我做的:

        private void Button_Click(object sender, RoutedEventArgs e)
    {
        //create the combo box
        var comboBox = new ComboBox();
        //add the items to it
        comboBox.Items.Add("1");
        comboBox.Items.Add("2");

        //if there are no items in the relative panel, then the first combo box should go at the top
        if (RelPanel.Children.Count == 0)
        {
            RelPanel.Children.Add(comboBox);
            RelativePanel.SetAlignTopWithPanel(comboBox, true);
        }
        else
        {
            //if there are items already, the new combo box goes below the last one added
            RelativePanel.SetBelow(comboBox, RelPanel.Children.Last());
            RelPanel.Children.Add(comboBox);
        }
    }

希望这对你有所帮助,也是你想要的。

编辑:您可以使用堆叠面板,但相对面板可让您更好地控制项目的放置。

答案 1 :(得分:0)

您可以这样添加组合框:

    private void button1_Click(object sender, EventArgs e)
    {
        ComboBox combobox = new ComboBox();
        combobox.Items.Clear();
        foreach (string item in new List<string>() { "a", "b", "c" })
        {
            combobox.Items.Add(item);
        }
        this.Controls.Add(combobox);
    }