C# 尝试在XAML中创建方形按钮时无法获取实际宽度/高度属性
我正在尝试制作一个正方形按钮,其尺寸相对于父元素的宽度(在Windows Phone 8.1应用程序中) 我找到了这样的解决方案:C# 尝试在XAML中创建方形按钮时无法获取实际宽度/高度属性,c#,xaml,windows-phone-8.1,C#,Xaml,Windows Phone 8.1,我正在尝试制作一个正方形按钮,其尺寸相对于父元素的宽度(在Windows Phone 8.1应用程序中) 我找到了这样的解决方案: <Button MinWidth="{Binding ActualHeight, RelativeSource={RelativeSource Self}}" MinHeight="{Binding ActualWidth, RelativeSource={RelativeSource Self}}"> Some co
<Button
MinWidth="{Binding ActualHeight, RelativeSource={RelativeSource Self}}"
MinHeight="{Binding ActualWidth, RelativeSource={RelativeSource Self}}">
Some content
</Button>
一些内容
以下是我如何使用它:
<Button
Grid.Row="0"
Grid.Column="0"
Grid.RowSpan="3"
HorizontalAlignment="Stretch"
MinWidth="{Binding ActualHeight, RelativeSource={RelativeSource Self}}"
MinHeight="{Binding ActualWidth, RelativeSource={RelativeSource Self}}">
blablabla
</Button>
喋喋不休
但是它只在XAML设计器中工作,并且只有当它渲染了button元素(因此它知道它的宽度),然后我粘贴MinWidth
和MinHeight
规则时才工作。如果我真的喜欢,我会达到预期效果:
在运行调试器后会被破坏:
有没有办法让它正常工作?
谢谢你的帮助 要使按钮成为方形,可以使用SquareGrid控件:
public class SquareGrid : Grid
{
protected override Size MeasureOverride(Size availableSize)
{
availableSize = base.MeasureOverride(availableSize);
return new Size(availableSize.Width, availableSize.Width);
}
protected override Size ArrangeOverride(Size finalSize)
{
finalSize = base.ArrangeOverride(finalSize);
Width = Height = finalSize.Width;
return new Size(finalSize.Width, finalSize.Width);
}
}
例如:
<SquareGrid>
<Button HorizontalAlignment="Stretch" VerticalAlignment="Stretch">blablabla</Button>
</SquareGrid>
喋喋不休
你知道吗?如果你不让它这样做,按钮的大小就已经与它的父控件相同了?@GlenThomas在我的项目中,按钮适合它的文本属性,这就是为什么我使用HorizontalAlignment=“Stretch”
什么是父控件?
。这里有一些
,它们定义了所需的宽度(以相对单位,如2*
),您可能想测量并排列修改后的尺寸?@PeterTorr MSFT,如果发现错误,请编辑答案。