views:

106

answers:

2

I'm learning WPF and can't figure out how to enfore my buttons to take a square shape.

Here is my XAML Markup:

<Window x:Class="Example"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Height="368" Width="333">
  <Window.Resources>
    <Style x:Key="ToggleStyle" BasedOn="{StaticResource {x:Type ToggleButton}}"
                            TargetType="{x:Type RadioButton}">
    </Style>
  </Window.Resources>
  <RadioButton Style="{StaticResource ToggleStyle}">
        Very very long text
  </RadioButton>
</Window>

Specifying explicit values for Width and Height attributes seems like a wrong idea - the button should calculate its dimensions based on its contents automagically, but keep its width and height equal. Is this possible?

+1  A: 

I think you want to bind button's width to its height, like this:

<Button Name="myButton"
Width="{Binding ElementName=myButton, Path=Height}"
Height="100">
Button Text
</Button>
n535
I think Gart wants it to still autosize to content, which is slightly trickier to accomplish. Also, rather than using `ElementName`, you could use `RelativeSource={RelativeSource Self}`, which is more easily portable.
Dan Puzey
@Dan Puzey, Thanks =)
n535
+2  A: 

Try this - it seems to work in Kaxaml:

<Button 
    MinWidth="{Binding ActualHeight, RelativeSource={RelativeSource Self}}" 
    MinHeight="{Binding ActualWidth, RelativeSource={RelativeSource Self}}">
  Some content
</Button>

(To test, I put a TextBox inside the button, 'cause it's an easy way to change content size without re-parsing xaml.)

Edit: sorry, should probably have specified it as a style to match your example:

<Style TargetType="Button" x:Key="SquareButton">
  <Setter Property="MinWidth" Value="{Binding ActualHeight, RelativeSource={RelativeSource Self}}" />
  <Setter Property="MinHeight" Value="{Binding ActualWidth, RelativeSource={RelativeSource Self}}" />
</Style>
Dan Puzey