Click here to Skip to main content
16,017,151 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:

I have 3 WPF buttons in a grid with 3 columns. I want each button to stretch to fill the contents of each cell, but only to a maximum width. Once that width has been achieved, I would like to then align each button according to it's grid column (left column button gets aligned to the left, middle column button gets centered, right column button gets aligned to the right). Here's the XAML I've go so far that isn't working:

XML
<Grid HorizontalAlignment="Stretch">
    <Grid.ColumnDefinitions>
        <ColumnDefinition />
        <ColumnDefinition />
        <ColumnDefinition />
    </Grid.ColumnDefinitions>
    <Button HorizontalAlignment="Left"
        Width="Auto" Grid.Column="0" MaxWidth="100">Overwrite</Button>
    <Button HorizontalAlignment="Center"
        Width="Auto" Grid.Column="1" MaxWidth="100">Skip</Button>
    <Button HorizontalAlignment="Right"
        Width="Auto" Grid.Column="2" MaxWidth="100">Cancel</Button>
</Grid>

That just makes the buttons size to their content (rather than to available space), but it aligns them properly. If you inspect the above XAML in Kaxaml, you'll see what I mean. What I'm trying to achieve is having these buttons align properly AND grow up to 100 units wide. From what I've seen so far, resizing and aligning appear to be too closely linked in WPF to achieve this.

Any idea of how to both stretch a button up to a maximum width AND align it horizontally once it has reached that maximum width?

Posted

How about adding two more "dummy" columns? Put your buttons in columns 1,3 and 5, and set the column's width to Auto and maximum size to 100 (not the button's). And for columns 2 and 4 set the width to *.
 
Share this answer
 
You're a flippin' genius! Don't know why I didn't think of that. Here's what I (read: you) came up with (and it works reasonably well):
XML
<Grid HorizontalAlignment="Stretch">
	<Grid.ColumnDefinitions>
		<ColumnDefinition MaxWidth="100" Width="*" />
		<ColumnDefinition Width="0.01*" />
		<ColumnDefinition MaxWidth="100" Width="*" />
		<ColumnDefinition Width="0.01*" />
		<ColumnDefinition MaxWidth="100" Width="*" />
	</Grid.ColumnDefinitions>
	<Button Grid.Column="0">b1</Button>
	<Button Grid.Column="2">b2</Button>
	<Button Grid.Column="4">b3</Button>
</Grid>

I had to set the width of the other columns to some small proportion because "Auto" was causing the grid to collapse those columns and a value of "1*" was causing the buttons to shrink prematurely. Thanks again, great idea!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900