views:

164

answers:

3

Suppose you have a window with multiple buttons such as Ok/Cancel or Yes/No/Cancel. All the buttons need to be the same width. Obviously this could be done by just guessing a number and hardwiring all of them to that number.

Is there a better way to do it, one that would take into account preferred/recommended sizes (just how wide should an Ok button be anyway? This is not a rhetorical question, I actually don't know the answer!), what's needed by the text of the longest caption, what happens if the font size is increased etc?

A: 

In the most general case, you want to create a Style in your section, then apply this style as desired. Now when you change the style, all buttons change.

Or you can change the Content of the button so that it autosizes to the text.

Dave
Thanks. But, correct me if I'm wrong, but wouldn't making a button autosize to the text, break the requirement that all buttons be the same width? And, isn't the style solution, just a particular way of implementing 'guess a number and hardwire all the buttons to that number'?
rwallace
Ah... I understand your requirement now, sorry! Daniel has a much better answer, then.
Dave
+3  A: 

There are several ways to do this:

1) Use a Grid for layout. Each Button gets its own Column, which is Star-sized. That way, all columns are the same size:

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*" />
        <ColumnDefinition Width="*" />
        <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>
    <Button Grid.Column="0">Yes</Button>
    <Button Grid.Column="1">No</Button>
    <Button Grid.Column="2">Cancel</Button>
</Grid>

2) You can have one item as "master size" and bind the width of all others to this item's width.

<StackPanel Orientation="Horizontal">
    <Button Name="MasterButton" Width="100">Yes</Button>
    <Button>
        <Button.Width>
            <Binding ElementName="MasterButton" Path="Width"/>
        </Button.Width>
        No
    </Button>
</StackPanel>

EDIT: In actual code, you probably will have Width="Auto". Since the other widths are based on the "master width", the button with the widest width (widest text) should be chosen.

Daniel Rose
+1 for recommending using panels in your first suggestion, but I'm really against hardcoding UI sizes.
Benny Jobigan
In the second case this was for demonstration that the binding is working.
Daniel Rose
+1  A: 

According to the MS User Experience Interaction Guidelines for Windows 7 and Windows Vista (p61), standard dimensions for command buttons are 50x14 DLU actual size (75x23 pixels). The guidelines further suggest you "try to work with [these] default widths and heights." Obviously, if you need more width to fit a clear label, then take more width.

Michael Zuschlag