Stackpanel对象在同一条线上?

时间:2013-12-23 14:19:09

标签: c# wpf combobox

回答,感谢Rohit Vats& Panagiotis Kanavos的答案非常有效!

我希望ComboBox与Stackpanel中的TextBox位于同一行,但是当边距相同时,它只是将它放在下面的行上。

单击按钮时会生成ComboBox和文本框。

C#代码:

int t = 0;
private void btnAddTitle_Click(object sender, RoutedEventArgs e)
{

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

        TextBox x = new TextBox();
        x.Name = "Title" + t;
        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.VerticalAlignment = System.Windows.VerticalAlignment.Top;
        x.Margin = new Thickness(0, 15, 0, 0);


        ComboBox y = new ComboBox();
        y.Name = "Combo" + t;
        y.Text = (t + 1).ToString();
        y.Height = 25;
        y.Width = 45;
        y.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
        y.VerticalAlignment = System.Windows.VerticalAlignment.Top;
        y.Margin = new Thickness(0, 15, 0, 0);

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


        spStandard.Children.Add(sp);

        t++;


}

    int q = 0;
    private void btnQuestion_Click(object sender, RoutedEventArgs e)
    {
        TextBox x = new TextBox();
        x.Name = "Question" + q;
        x.Text = "Question...";
        x.FontStyle = FontStyles.Italic;
        x.TextWrapping = TextWrapping.Wrap;
        x.Height = 25;
        x.Width = 500;
        x.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
        x.AcceptsReturn = true;
        x.Margin = new Thickness(70, 15, 0, 0);
        spStandard.Children.Add(x);
        q++;
}

正在发生的事情的图片:

http://i.stack.imgur.com/F3Nk8.png

正如您所见,当我需要将文本框放在文本框的左侧时,它会被置于文本框下面。

有什么方法可以解决这个问题,但保留Stackpanel?

(之前我问了一个类似的问题,但并不是出于这个原因。)

2 个答案:

答案 0 :(得分:2)

您应将其添加到StackPanel sp中,方向设置为Horizontal,而不是直接添加到外部面板。

更改

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

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

答案 1 :(得分:2)

看起来您正在将元素添加到错误的StackPanel中。而不是将它们添加到sp,其中Orientation = Orientation.Horizontal将它们添加到spStandard。

你应该改变:

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

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