4

I have the following:

<DockPanel Height="25" HorizontalAlignment="Stretch">
    <Button Content="Add" x:Name="bAdd" DockPanel.Dock="Left" />
    <Button Content="Remove" x:Name="bRemove" DockPanel.Dock="Right" />
</DockPanel>

Can someone suggest me how to make both the buttons have equal width without setting the Width property of the buttons manually?

Elmo
  • 6,409
  • 16
  • 72
  • 140

3 Answers3

10

If you absolutely don't want to set the Width propety, you can just use a Grid :

<Grid Height="25" HorizontalAlignment="Stretch">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*" />
        <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>
    <Button Grid.Column="0" Content="Add" x:Name="bAdd" />
    <Button Grid.Column="1" Content="Remove" x:Name="bRemove" />
</Grid>

They will both have the same Width this way

Damascus
  • 6,553
  • 5
  • 39
  • 53
  • 1
    Was just about to hit "Post answer" when I reloaded and saw this - this is by far the easiest approach for dynamic, yet equal-width controls. – JerKimball Dec 31 '12 at 21:44
  • I second this. What I normally do is this. – It'sNotALie. Dec 31 '12 at 21:58
  • 1
    Classic stackoverflow situation: about to hit post answer, somebody just did :) On a more related note, the * value for width & height is one of those things which just make WPF awesome. I can't use Winforms anymore now! – Damascus Dec 31 '12 at 21:59
7
<UniformGrid Columns="2">
 <Button Content="Ok" Grid.Column="0"/>
 <Button Content="Cancel" Grid.Column="1"/>
</UniformGrid>
Sebastian Ax
  • 1,240
  • 12
  • 11
Amir Touitou
  • 3,141
  • 1
  • 35
  • 31
0

In addition to the @Amir's answer you can control the numbers of buttons dynamically by binding Visbility.

<UniformGrid Rows="1">
 <Button Content="Ok" Visiblity="{Binding IsShowOkayButton, Converter={...}"/>
 <Button Content="Cancel" Visiblity="{Binding IsShowCancelButton, Converter={...}}"/>
</UniformGrid>

Use with enumeration: (Assuming that ConfirmType and IsShowCancelButton in the same ViewModel)

public enum ConfirmType { Confirm, ConfirmOrCancel }

public ConfirmType ConfirmType { get => _ConfirmType; 
            set {
                switch (_ConfirmType)
                {
                    case ConfirmType.Confirm:
                        IsShowCancelButton = false;
                        break;
                    case ConfirmType.ConfirmOrCancel:
                        IsShowCancelButton = true;
                        break;
                }
                // Your RaisePropertyChanged code here
            }
        }
Mark Choi
  • 420
  • 6
  • 16