#431 – Binding a Control’s Width to Its Height
November 16, 2011 5 Comments
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>
Pingback: Dew Drop – November 16, 2011 | Alvin Ashcraft's Morning Dew
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)?
Stefan, yes I think you answered your own question–you could bind to the minimum of the two values to get what you want.
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.
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.