我是WPF的新手。我在按鈕單擊上在Canvas上添加矩形。當我從TextBox設置特定矩形的高度。它與子矩形重疊。例如:如何使用C#在WPF中調整大小的父矩形旁邊的矩形?
例如:當有3個矩形Height=100
,Width=200
&當我設置高度Second Rectangle to 150
。那麼子Rectangle
必須在第二個矩形&不得在第三個矩形上重疊後出現。可能嗎?
static int val=0;
List<UIElement> itemstoremove = new List<UIElement>();
private void BtnAdd_Click(object sender, RoutedEventArgs e)
{
int heigt = 0;
int wegt = 0;
if (!string.IsNullOrEmpty(txtHeight.Text) && !string.IsNullOrEmpty(txtWidth.Text))
{
heigt = int.Parse(txtHeight.Text);
wegt = int.Parse(txtWidth.Text);
}
rect = new Rectangle();
rect.Stroke = Brushes.Red;
rect.StrokeThickness = 2;
rect.Height = heigt;
rect.Width = wegt;
Canvas.SetLeft(rect, 10);
Canvas.SetTop(rect, (rect.Height) * val);
rect.Tag = val;
canvasboard.Children.Add(rect);
val = val + 1;
//canvasboard is Canvas object
foreach (UIElement ui in canvasboard.Children)
{
if (ui.GetType() == typeof(Rectangle))
{
itemstoremove.Add(ui);
}
}
}
修改高度&寬度:
private void BtnModify_Click(object sender, RoutedEventArgs e)
{
int heigt = 0;
int wegt = 0;
if (!string.IsNullOrEmpty(txtHeight.Text) && !string.IsNullOrEmpty(txtWidth.Text))
{
heigt = int.Parse(txtHeight.Text);
wegt = int.Parse(txtWidth.Text);
}
Rectangle rectToRemove;
foreach (UIElement ui in itemstoremove)
{
if (ui.GetType() == typeof(Rectangle) && ((Rectangle)ui).Tag.ToString() == txtModifyRect.Text)
{
rectToRemove = ui as Rectangle;
//itemstoremove.Remove(rectToRemove);
rectToRemove.Height = heigt;
rectToRemove.Width = wegt;
//canvasboard.Children.Remove(rectToRemove);
break;
}
}
}
這工作得很好。 只是我想防止彼此重疊Rectangle
,並且必須使用自動調整一個接一個出現。
幫助讚賞!
你的意思是我必須添加矩形到WrapPanel?我是新來的,所以..! –
這是一個非常好的建議,但作者希望將它們放在另一個之下,至少我認爲他在看到'Canvas.SetLeft(rect,10)後需要它。 Canvas.SetTop(rect,(rect.Height)* val);'.. – quetzalcoatl
@SHEKHARSHETE:是的,他的確是這個意思。 WrapPanel將成爲矩形的容器,然後矩形會像HTML頁面上的文本一樣進行佈局:只要還有剩餘空間,然後換行到「新行」。 – quetzalcoatl