Q:

WPF - Dynamically add button next to textbox

I am creating Label, Textbox and a button dynamically. I need Button to appear in the same line as textbox to its right.
This is the code i am using:
    Label lbl = new Label()
    {
        Content = "Some Label",
        HorizontalAlignment = HorizontalAlignment.Left,
        VerticalAlignment = VerticalAlignment.Top,
        HorizontalContentAlignment = HorizontalAlignment.Center,
        VerticalContentAlignment = VerticalAlignment.Center,
        Height = 28,
    };

    TextBox tb = new TextBox()
    {
        Text = "Some Text",
        IsReadOnly = true,
    };

    Button btn = new Button()
    {
        Content = "Click Me",
        HorizontalAlignment = HorizontalAlignment.Left
        Margin = new Thickness(tb.ActualWidth),
    };

I am assigning Button Margin to the Right of TextBox but it still appears in the next line under the textbox.
What am i doing wrong here?

A:

You can use StackPanel to solve your problem:
StackPanel spMain = new StackPanel() { Orientation = Orientation.Vertical };

Label lbl = new Label()
  {
      Content = "Some Label",
      HorizontalAlignment = HorizontalAlignment.Left,
      VerticalAlignment = VerticalAlignment.Top,
      HorizontalContentAlignment = HorizontalAlignment.Center,
      VerticalContentAlignment = VerticalAlignment.Center,
      Height = 28,
  };

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

TextBox tb = new TextBox()
{
    Text = "Some Text",
    IsReadOnly = true,
};

Button btn = new Button()
{
    Content = "Click Me",
    HorizontalAlignment = HorizontalAlignment.Left,
    Margin = new Thickness(tb.ActualWidth),
};

spInner.Children.Add(tb);
spInner.Children.Add(btn);

spMain.Children.Add(lbl);
spMain.Children.Add(spInner);

You can check following link for more information: 
http://msdn.microsoft.com/en-us/library/system.windows.controls.stackpanel.orientation.aspx

