2013-07-12 3 views
1

WPF 응용 프로그램에 Canvas이 있습니다. 버튼 클릭시 Rectangle을 추가하고 있습니다. Width은 고정이지만 Height은 사용자가 TextBox/GridCell에 입력 한 값입니다.C#을 사용하여 WPF에서 캔버스에 다른 세로로 직사각형을 추가하는 방법?

Height을 지정하여 Canvas에 사각형을 추가 할 때. 그것은 직사각형을 추가하지만, 다른 직후에 나타나지 않습니다. 어떤 생각? .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; 
    } 

enter image description here 이것은 사각형을 추가하지만 캔버스에 다른 정확히 한 후.

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

참고 :이 양식 WrapPanel 또는 StackPanel를 사용하지 못할. 및 기존 코드를 변경하고 싶습니다.

도움말 감사드립니다!

+0

설명에서 시나리오를 다시 만들 필요가 없도록 .xaml 파일의 최소 필수 비트를 공유 할 수 있습니까? – RQDQ

+0

안녕하세요 @RQDQ 내 코드를 수정했는지 확인하십시오! 버튼을 .. 추가하십시오! –

+0

오타입니다 : "rect.Height = txtheight.Text"? 왜냐하면 rect.Height 두 번 문자열이 필요합니다. –

답변

2

을, 당신은 클래스에 새로운 변수를 추가 할 필요없이 그것을 할 수 있습니다 범위뿐만 아니라.

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); 
} 
+0

헤이 @Viv 덕분에 많이 .. ..! :) –

2

모든 사각형의 결합 된 높이를 유지하는 지역 변수 저장보십시오 : 귀하는 추가 모든이 Canvas에 수직으로 연속적인 요소 인 경우

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

안녕하세요 @ 리차드 전자 이것도 작동하지만 내가 Viv 솔루션을 사용 ... 고마워! –