15

What's the best control to arrange buttons horizontally across a window in WPF? I am having trouble arranging the buttons evenly while resizing the window. I tried to use the stack panel but the buttons just stay at their position and do not space out to fill up the window space. Tried to use the dock panel as well but no luck yet.

Can anybody suggest me a good way to do it or tell me if I am doing anything wrong?

Saurabh Lalwani
  • 705
  • 2
  • 7
  • 15

3 Answers3

22

How about a Grid or, even easier, UniformGrid?

Kent Boogaart
  • 175,602
  • 35
  • 392
  • 393
8

I'd like to see an example of how to easily get the UniformGrid to space the buttons equally if they are intended to retain their "natural" widths rather than being forced to have uniform widths.

In the meantime, perhaps this isn't the best solution, but it seems to work for me and might help the next person:

<Grid.ColumnDefinitions>
  <ColumnDefinition Width="Auto" />
  <ColumnDefinition Width="*" />
  <ColumnDefinition Width="Auto" />
  <ColumnDefinition Width="*" />
  <ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>

<Button x:Name="FirstBtn" Grid.Column="0" Content="_First" />
<!-- Skip column 1 so it will provide flexible space -->
<Button x:Name="SecondBtn" Grid.Column="2" Content="_Second" />
<!-- Skip column 3 -->
<Button Name="ThirdBtn" Grid.Column="4" Content="_Third" />
Charles Jenkins
  • 340
  • 4
  • 10
  • If the number of children is known design time, this might be the next best decision. And maybe you can subclass grid to allow Children.Add() functionality where you achieve a similar Column composition behind the scenes. – Tormod Nov 15 '21 at 09:28
4

What are you doing wrong? You are ignoring MSDN section on the layout system in WPF :).

You can use Grid and set HorizontalAlignment/VerticalAlignment of buttons to Center, and grid column width should be *.

Lennart
  • 9,657
  • 16
  • 68
  • 84
Anvaka
  • 15,658
  • 2
  • 47
  • 56