我是 WPF 的新手。我在按钮单击时在画布上一个接一个地添加矩形。当我从 TextBox 设置特定矩形的高度时。它与子矩形重叠。
例如:。 当有 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
彼此重叠,并且必须通过自动调整一个接一个地出现。
帮助赞赏!