WPF 动态布局:如何强制平方比例(宽度等于高度)? [英] WPF dynamic layout: how to enforce square proportions (width equals height)?
问题描述
我正在学习 WPF,但不知道如何使我的按钮变成方形.
I'm learning WPF and can't figure out how to enfore my buttons to take a square shape.
这是我的 XAML 标记:
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>
为 Width
和 Height
属性指定显式值似乎是一个错误的想法 - 按钮应该根据其内容自动计算其尺寸,但保持其宽度和高度相等.这可能吗?
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?
推荐答案
试试这个 - 它似乎在 Kaxaml 中工作:
Try this - it seems to work in Kaxaml:
<Button
MinWidth="{Binding ActualHeight, RelativeSource={RelativeSource Self}}"
MinHeight="{Binding ActualWidth, RelativeSource={RelativeSource Self}}">
Some content
</Button>
(为了测试,我在按钮内放置了一个 TextBox,因为这是一种无需重新解析 Xaml 即可更改内容大小的简单方法.)
(To test, I put a TextBox inside the button, because that's an easy way to change content size without re-parsing the Xaml.)
抱歉,应该将其指定为与您的示例相匹配的样式:
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>
这篇关于WPF 动态布局:如何强制平方比例(宽度等于高度)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!