我有两个UserControl
只有一个/两个文本块。在我的窗口中,我添加了第一个UserControl
情侣o'对于每个循环和第二个用户控件的时间,我只是将其添加到最后,这意味着我只有1 UserControl2
。
public class test
{
UserControl1 btn = new UserControl1;
private void thread1()
{
foreach (var item in mycollection)///i am not including the actual iteration target because it is a class and then the post might be too huge
{
mystack.Children.Add(btn);
}
mystack.Children.Add(new UserControl2);
}
请注意,我只在UserControl1
循环中添加foreach
,但我在循环外添加UserControl2
,这意味着我要将其添加一次。
无论如何,我可以在mystack
循环中迭代我添加到foreach
的所有控件,如:
foreach (var control in mystack.Children)
{
////My codes here
}
正如我前面提到的,UserControl
中添加了两种类型的StackPanel
。我如何只迭代一种UserControl
?我的意思是,如果我想只遍历UserControl1
(mystack)中的Stackpanel
s?
我尝试过类似的事情:
private void thread2()
{
foreach (UserControl1 control in mystack.Children)
{
}
//////Or
for (i = o; i <= mystack.children - 1; i++)
{
btn.height = 10 /// my other codes here :)
}}
但他们都抛出Unable to cast object of type UserControl2 to UserControl1
异常,这意味着它正在遍历所有控件(UserControl1
和UserControl2
):(
看到帖子中的第一个黑色代码?有些人可能会建议我在第一个foreach
循环中做任何我想做的事情但是我不能,这必须在不同的线程中完成(thread1
中的第一个循环其余的都在thread2
......所以,我该怎样实现这个目标?
答案 0 :(得分:0)
使用方法OfType按类型过滤子项
foreach (UserControl1 control in mystack.Children.OfType<UserControl1>())
{
}
答案 1 :(得分:-2)
如果做一些反思怎么办?
Type t = typeof(yourControl);
if (t == typeof(int)) // or whatever you need
// Some code here
typeof采用类型名称(在编译时指定)。 或者您也可以使用GetType:
if(yourcontrol.GetType() == typeof(yourControl))
//code here
GetType获取实例的运行时类型。