Search code examples
.netwpfxaml

What is the intended way to make a label and text box side by side in WPF?


I'll often use this:

<StackPanel>
  <StackPanel Orientation="Horizontal">
    <Label>Username:</Label>
    <TextBox />
  </StackPanel>
  <StackPanel Orientation="Horizontal">
    <Label>Password:</Label>
    <PasswordBox />
  </StackPanel>
</StackPanel>

But it is such a common scenario, I feel like there is a way with less markup.

Also, is there a performance impact of using so many stack panels?


Solution

  • There are two primary ways to do this, StackPanels and Grid Definitions, and Grid does not provide any less markup than StackPanel. I personally like to use Grid Definitions a lot more. They take awhile to get use to, and every now and then I still use a StackPanel, but overall they feel a lot cleaner when you get use to them. Here is a great tutorial on how to use them.

    A reference that might also help is WPF Grid Vs. StackPanel.