Cur*_*tis 1 c# wpf binding ellipse textblock
我在Grid.Row和Grid.Column中绘制了一个椭圆.Row总是高于Column宽.
我想绘制一个填充网格列宽度的椭圆,以及它的高度使其成为一个完美的圆.
我还想在上面的椭圆的中心画一个数字.基本上以一个以数字为中心的圆圈结束.
我可以在我的Ellipse和包含数字的TextBlock上轻松设置HorizontalAlignment ="Stretch".这照顾了我的宽度.但是,即使Grid.Column宽度发生变化,如何使Ellipse和TextBlock的高度始终与其宽度匹配?
这里有一些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"/>
Run Code Online (Sandbox Code Playgroud)
感谢你的帮助.我最终使用了Herdo的答案.只需将HorizontalAlignment设置为Stretch,然后将高度绑定到椭圆的实际宽度即可.我对椭圆和文本块做了同样的事情:
<Ellipse HorizontalAlignment="Stretch" Height="{Binding ActualWidth, RelativeSource={RelativeSource Self}}"/>
<TextBlock HorizontalAlignment="Stretch" Height="{Binding ActualWidth, RelativeSource={RelativeSource Self}}"/>
Run Code Online (Sandbox Code Playgroud)
假设你有一个Grid包含Ellipse,你可以使用该ActualWidth属性,并保持拉伸,而不设置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>
Run Code Online (Sandbox Code Playgroud)
请考虑MSDNActualWidth上该属性的评论:
因为ActualWidth是一个计算值,所以您应该知道,由于布局系统的各种操作,可能会有多个或增量报告的更改.布局系统可以计算子元素所需的度量空间,父元素的约束等等.
因此,以下示例代码......
<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>
Run Code Online (Sandbox Code Playgroud)
...将导致此行为(宽度/高度将每次更新,容器 - Grid在本例中 - 更改其布局):