gpt4 book ai didi

c# - 如何将 WPF 椭圆的高度绑定(bind)到它自己的宽度?

转载 作者:太空宇宙 更新时间:2023-11-03 17:20:04 39 4
gpt4 key购买 nike

我在 Grid.Row 和 Grid.Column 中绘制了一个椭圆。行总是比列宽。

我想画一个椭圆来填满网格列的宽度,谁的高度使它成为一个完美的圆。

我还想在上面椭圆的中心精确地画一个数字。基本上以一个以数字为中心的圆圈结束。

我可以轻松地在我的 Ellipse 和包含数字的 TextBlock 上设置 Horizo​​ntalAlignment="Stretch"。这为我处理了宽度。但是,如何使 Ellipse 和 TextBlock 的高度始终与其宽度匹配,即使在 Grid.Column 宽度发生变化时也是如此?

下面是一些 XAML 来说明这一点。在下面的 XAML 中,我希望硬编码的“63”基于 Grid.Column 宽度或椭圆的宽度字段:

    <Ellipse Grid.Row="1" Grid.Column="0" HorizontalAlignment="Stretch" Height="63" Stroke="Black" StrokeThickness="3" VerticalAlignment="Top"/>
<TextBlock Grid.Row="1" Grid.Column="0" Width="63" Height="63" VerticalAlignment="Top" Text="1" TextAlignment="Center" FontSize="42" FontWeight="Bold"/>

感谢您的帮助。我最终使用了 Herdo 的答案。只需将 Horizo​​ntalAlignment 设置为 Stretch,然后将高度绑定(bind)到椭圆的实际宽度。我对椭圆和文本 block 做了同样的事情:

    <Ellipse HorizontalAlignment="Stretch" Height="{Binding ActualWidth, RelativeSource={RelativeSource Self}}"/>
<TextBlock HorizontalAlignment="Stretch" Height="{Binding ActualWidth, RelativeSource={RelativeSource Self}}"/>

最佳答案

假设您有一个包含椭圆的 Grid,您可以使用 ActualWidth 属性,并保持拉伸(stretch)状态,而无需设置 Width 属性- 允许您在不引用父容器的情况下使用 Ellipse:

<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/> <!-- Or whatever width -->
</Grid.ColumnDefinitions>

<Ellipse Grid.Column="0"
HorizontalAlignment="Stretch"
Height="{Binding ActualWidth, RelativeSource={RelativeSource Self}}"/>
</Grid>

请考虑 MSDN 上对 ActualWidth 属性的备注:

Because ActualWidth is a calculated value, you should be aware that there could be multiple or incremental reported changes to it as a result of various operations by the layout system. The layout system may be calculating required measure space for child elements, constraints by the parent element, and so on.

因此,下面的示例代码...

<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="30"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>

<Ellipse Grid.Row="1"
Grid.Column="1"
HorizontalAlignment="Stretch"
Fill="Red"
Height="{Binding ActualWidth, RelativeSource={RelativeSource Self}}"/>
</Grid>

...将导致此行为(宽度/高度每次都会更新,容器 - 在本例中为 Grid - 更改其布局):

enter image description here

关于c# - 如何将 WPF 椭圆的高度绑定(bind)到它自己的宽度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29154068/

39 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com