我正在尝试选择一个不是Control - OvalShape的东西。
这可以找到一个按钮
string y = "btn_down_" + x;
Button button = this.Controls.Find(y, true)[0] as Button;
我怎么能做同样的事情来找到一个OvalShape例如:(这显然不起作用)
string y = "ovalShape_" + x;
OvalShape light = this.Controls.Find(y, true)[0] as OvalShape;
_____解_____
string z = "ovalShape" + (21-x);
OvalShape light = shapeContainer2.Shapes.OfType<OvalShape>().FirstOrDefault(ov => ov.Name == z);
答案 0 :(得分:1)
从docs我看到在ShapeContainer上首先添加了一个Shape,它只是一个容器控件。
然后,ShapeContainer有一个名为Shapes的属性,其类型为ShapeCollection,并公开列表方法,如Contains。
假设你已经像这样设置了所有内容:
Microsoft.VisualBasic.PowerPacks.ShapeContainer canvas =
new Microsoft.VisualBasic.PowerPacks.ShapeContainer();
Microsoft.VisualBasic.PowerPacks.OvalShape oval1 =
new Microsoft.VisualBasic.PowerPacks.OvalShape();
// Set the form as the parent of the ShapeContainer.
canvas.Parent = this;
for(int i =0;i < canvas.Count; i++)
{
var shape = (Shape)canvas.Item[i];
//now check if shape is your oval by looking at it's properties.
}
//You could also do this:
// (But this means you have to store a reference to your shape somewhere
// as some sort of global, not very good design.)
OvalShape myShape = ..
int index = canvas.IndexOf(myShape);
canvas.Item[index];//returns your shape.
如果您使用for循环方法,则可以检查形状的Name属性。您也可以使用Tag属性;将代码设置为"OvalShape"
,然后在循环中检查:if(shape.Tag == "OvalShape") {..
。
答案 1 :(得分:1)
根据@ gideon的回答中提供的一些链接,你可以这样试试:
首先获取默认的ShapeContainer,然后在类型为OvalShape
且名称等于y
的容器内搜索形状。
string y = "ovalShape_" + x;
var shapeContainer = this.Controls.OfType<ShapeContainer>().FirstOrDefault();
OvalShape light = shapeContainer.Shapes.OfType<OvalShape>().FirstOrDefault(o => o.Name == y);
此代码对我来说很好,但将OvalShape
拖到表单后生成的名称类似于"ovalShape" + x
而不是"ovalShape_" + x
。