1

我的 WPF 应用程序中有一个Canvas。我正在添加Rectangleon 按钮单击。Width是固定的,但是Height是用户在 中输入的值TextBox/GridCell

当我Canvas通过指定添加矩形时Height。它添加了矩形,但它没有一个接一个地出现。任何想法?

在 .xaml.cs 中:

int width=200;
Reactangle rect;
 static int val=0;
  Protected void Add()
  {
            rect = new Rectangle();
            rect.Stroke = Brushes.Red;
            rect.StrokeThickness = 1;
            rect.Height = Convert.ToInt32(txtheight.Text);
            rect.Width = width;
            Canvas.SetLeft(rect,100);
            Canvas.SetTop(rect,rect.Height);
            rect.Tag = val;
            canvasboard.Children.Add(rect);
            val=val+1;
   } 

在此处输入图像描述 这会在画布上一个接一个地添加矩形,但不是一个接一个。

<Canvas Name="canvasboard" Background="White"  Margin="2">
        </Canvas>
<TextBox Name="txtheight" Width="150"/>

注意:我不能使用WrapPanelorStackPanel这个表格。并希望对现有代码进行更改。

帮助赞赏!

4

2 回答 2

2

尝试存储一个保持所有矩形组合高度的局部变量:

    private double _top = 0;

    protected void Add()
    {
        var rect = new Rectangle();
        rect.Stroke = Brushes.Red;
        rect.StrokeThickness = 1;
        rect.Height = double.Parse(txtheight.Text);
        rect.Width = 20;
        Canvas.SetLeft(rect, 100);
        Canvas.SetTop(rect, _top);
        _top += rect.Height;
        rect.Tag = val;
        canvasboard.Children.Add(rect);
        val = val + 1;
    }
于 2013-07-12T12:59:30.490 回答
2

如果您添加的所有元素都是垂直添加到 this 中的顺序元素Canvas,那么您也可以这样做,而无需在类范围内添加新变量。

private void Add() {
  rect = new Rectangle {
    Stroke = Brushes.Red,
    StrokeThickness = 1,
    Height = Convert.ToDouble(txtheight.Text),
    Width = width
  };
  Canvas.SetLeft(rect, 100);
  double canvasTop = 0.0;
  if (canvasboard.Children.Count > 0) {
    var lastChildIndex = canvasboard.Children.Count - 1;
    var lastChild = canvasboard.Children[lastChildIndex] as FrameworkElement;
    if (lastChild != null)
      canvasTop = Canvas.GetTop(lastChild) + lastChild.Height + 1;
  }
  Canvas.SetTop(rect, canvasTop);
  rect.Tag = val++;
  canvasboard.Children.Add(rect);
}
于 2013-07-12T13:07:52.217 回答