C# WPF how to draw a circle which extends to fill its parent and remains a circle in code behind
我必须在网格中画一个圆。 该网格必须按比例适应其父网格的"列/行"定义所定义的高度和宽度。
现在,如果我拉伸,它将填充所有空间并变成省略号,而我希望它是一个圆。
简而言之,父网格像这样按比例适应
然后在例程中添加以下代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | public void RadialPercentage(Grid grd ) { Ellipse elpExt = new Ellipse(); elpExt.Stroke = Brushes.Green; elpExt.StrokeThickness = 4; //elpExt.Margin = new Thickness(0); //elpExt.HorizontalAlignment = HorizontalAlignment.Center; elpExt.VerticalAlignment = VerticalAlignment.Stretch; grd.Children.Add(elpExt); Ellipse elpInt = new Ellipse(); elpInt.Stroke = Brushes.Blue; elpInt.StrokeThickness = 4; elpInt.Margin = new Thickness(20); //elpInt.Width = elpInt.Height = dim-20; //elpInt.HorizontalAlignment = HorizontalAlignment.Center; elpInt.VerticalAlignment = VerticalAlignment.Stretch; grd.Children.Add(elpInt); return; } |
但是效果如下:
因此即使我只放置垂直约束而不是水平约束,它也会在垂直和水平方向上拉伸。 如果将其设置为居中,则椭圆会崩溃。
为了解决问题,即使我不确定这样做是否正确,我也尝试查看父网格的权重/高度,但显然这些值和实际值都设置为零。
谢谢你的帮助
帕特里克
将
1 2 3 4 5 6 7 8 9 10 11 12 | var ellipse = new Ellipse(); var binding = new Binding(Ellipse.ActualHeightProperty.Name) { RelativeSource = new RelativeSource(RelativeSourceMode.Self), Mode = BindingMode.OneWay }; ellipse.VerticalAlignment = VerticalAlignment.Stretch; ellipse.HorizontalAlignment = HorizontalAlignment.Center; BindingOperations.SetBinding(ellipse, Ellipse.WidthProperty, binding); |
每次调整父
您应该将
1 2 3 4 5 6 7 | <Grid Name ="MyGrid" SizeChanged ="MyGridSizeChanged"> <!-- rows and columns definitions --> <Ellipse Name ="MyEllipse" Grid.Row ="i" Grid.Column ="j" /> </Grid> |
现在,每次
1 2 3 4 5 6 7 8 9 10 | void MyGridSizeChanged(object sender, SizeChangedEventArgs e) { if (sender is Grid myGrid) { var cellHeight = myGrid.RowDefinitions[Grid.GetRow(MyEllipse)].ActualHeight; var cellWidth = myGrid.ColumnDefinitions[Grid.GetColumn(MyEllipse)].ActualWidth; var newSize = Math.Min(cellHeight, cellWidth); MyEllipse.Height = newSize; MyEllipse.Width = newSize; } } |