#431 – Binding a Control’s Width to Its Height

Since you can bind a property of a control to a different property on that same control, you could bind a control’s width to its height to force the control to  always be square.

In the example below, the Button control’s width changes as the container is resized, since its HorizontalAlignment is set to Stretch.  The Height of the Button is then bound to the ActualWidth property, so that the height always matches the width.

    <StackPanel>
        <Button HorizontalAlignment="Stretch"
                Height="{Binding Path=ActualWidth, RelativeSource={RelativeSource Self}}"
                Content="Height set to Width"
                Margin="5" Padding="5"/>
    </StackPanel>


About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

5 Responses to #431 – Binding a Control’s Width to Its Height

  1. Pingback: Dew Drop – November 16, 2011 | Alvin Ashcraft's Morning Dew

  2. Stefan says:

    Is there a way to prevent the control from partially disappearing when the main windows width ist larger than its size? Somethinh like binding the Width to the minimum of (mainWindow.ActualHeight, mainWindow.ActualWidth)?

    • Sean says:

      Stefan, yes I think you answered your own question–you could bind to the minimum of the two values to get what you want.

      • Phil says:

        Is there an easy way to do that?
        My idea would be to make a Minimum converter using IMultiValueConverter, unless there is some built-in functionality with which I am not familiar.

      • Sean says:

        I think that doing this in a converter is the most sensible way to do what you’re wanting to do, in a pretty easy fashion.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: