Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
265 views
in Technique[技术] by (71.8m points)

xaml - WPF dynamic layout: how to enforce square proportions (width equals height)?

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?

question from:https://stackoverflow.com/questions/2981705/wpf-dynamic-layout-how-to-enforce-square-proportions-width-equals-height

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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, because that's an easy way to change content size without re-parsing the 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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...