C#WPF如何绘制一个圆以扩展以填充其父级并在后面的代码中保持一个圆

C# WPF how to draw a circle which extends to fill its parent and remains a circle in code behind

我必须在网格中画一个圆。 该网格必须按比例适应其父网格的"列/行"定义所定义的高度和宽度。
现在,如果我拉伸,它将填充所有空间并变成省略号,而我希望它是一个圆。

简而言之,父网格像这样按比例适应
enter image description here

然后在例程中添加以下代码:

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;
}

但是效果如下:

enter image description here

因此即使我只放置垂直约束而不是水平约束,它也会在垂直和水平方向上拉伸。 如果将其设置为居中,则椭圆会崩溃。

为了解决问题,即使我不确定这样做是否正确,我也尝试查看父网格的权重/高度,但显然这些值和实际值都设置为零。

谢谢你的帮助
帕特里克


Width的绑定设置为椭圆的ActualHeight并将HorizontalAlignment设置为Center怎么办? 像这样:

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);


每次调整父Grid的大小时,都可以更新Ellipse的大小。

您应该将SizeChanged Event添加到Grid中。 XAML示例:

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>

现在,每次Grid调整大小时,都会执行MyGridSizeChanged函数。 您应该在其中添加代码,该代码将Ellipse的大小设置为等于所包含单元格的最小边。 C#示例:

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;
    }
}