C#WPF如何绘制一个扩展为填充其父级的圆圈,并在

时间:2017-05-28 12:54:04

标签: c# wpf grid constraints ellipse

我必须在网格中绘制一个圆圈。该网格必须按比例调整其父网格的列/行定义定义的高度和宽度。 现在,如果我放置拉伸它将填满所有空间并成为省略号,而我希望它是一个圆圈。

好吧,简而言之,父网格会按比例调整 enter image description here

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

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

因此即使我只放置垂直约束而不是水平约束,它也会纵向和横向拉伸。如果我将其设置为中心,则椭圆会折叠。

为了解决这个问题,即使我不确定这是正确的做法,我试着看看父网格的重量/高度,但显然这些值和实际值都设置为零。 / p>

感谢您的帮助 帕特里克

2 个答案:

答案 0 :(得分:3)

如何设置Width与椭圆ActualHeight的绑定并将HorizontalAlignment设置为Center呢?像这样:

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 :(得分:0)

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

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

<Grid Name        = "MyGrid"
      SizeChanged = "MyGridSizeChanged">
  <!-- rows and columns definitions -->
  <Ellipse Name        = "MyEllipse"
           Grid.Row    = "i"
           Grid.Column = "j" />
</Grid>

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

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