简体   繁体   English

在 WPF 中将形状放入网格中

[英]Put shapes in a grid in WPF

I'm trying to dynamicaly add a shape to a grid, I'm creating and setting it this way :我正在尝试动态地向网格添加一个形状,我正在以这种方式创建和设置它:

Rectangle theRect = new Rectangle();
currentRect = theRect;

theRect.VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Top;
theRect.HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Left;

theRect.Margin = new Thickness(oldPos.X,oldPos.Y,0,0);

theRect.StrokeThickness = brushWidht;
theRect.Stroke = new SolidColorBrush(brushColor);

theRect.Height = newPoint.Y - oldPos.Y;
theRect.Width = newPoint.X - oldPos.X;

theBoard.Children.Add(theRect);

But it sticks to the corner of "theBoard" which is the grid where I put it.但它粘在“theBoard”的角落,这是我放置它的网格。 Does anybody can help me with this ?有人可以帮我解决这个问题吗? Thanks.谢谢。

Since you've decided to have a Grid for the parent, I suppose you're trying to put your shape in different "cells", ie in different rows and columns.由于您决定为父级设置一个Grid ,我想您正试图将您的形状放在不同的“单元格”中,即在不同的行和列中。 You can do that with the following code:您可以使用以下代码执行此操作:

Grid.SetRow(theRect, 1);
Grid.SetColumn(theRect, 1);

If you want to set the absolute position of the shape in the parent then a Canvas would be a better choice.如果您想在父级中设置形状的绝对位置,那么Canvas将是更好的选择。 In this case you could set the offset of the shape inside the parent using the following code:在这种情况下,您可以使用以下代码在父级内部设置形状的偏移量:

Canvas.SetLeft(theRect, oldPos.X);
Canvas.SetTop(theRect, oldPos.Y);

I hope this answers your question.我希望这回答了你的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM