C# 在stackPanel WPF c中只循环一种类型的usercontrol#
我有两个C# 在stackPanel WPF c中只循环一种类型的usercontrol#,c#,wpf,loops,C#,Wpf,Loops,我有两个UserControl,只有一个/两个文本块。在我的窗口中,我为每个循环添加第一个UserControl两次,第二个用户控件,我只在最后添加它,这意味着我只有1个UserControl2 public class test { UserControl1 btn = new UserControl1; private void thread1() { foreach (var item in mycollection)///i am not including the actual
UserControl
,只有一个/两个文本块。在我的窗口中,我为每个循环添加第一个UserControl
两次,第二个用户控件,我只在最后添加它,这意味着我只有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);
}
请注意,我只在foreach
循环中添加了UserControl1
,但在循环外添加了UserControl2
,这意味着我只添加了一次
无论如何,我可以在foreach
循环中迭代添加到mystack
的所有控件,如:
foreach (var control in mystack.Children)
{
////My codes here
}
如前所述,有两种类型的UserControl
s添加到StackPanel
。如何仅迭代一种类型的UserControl
?我的意思是,如果我只想从Stackpanel
(mystack)遍历UserControl1
,该怎么办
我试过这样的方法:
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 :)
}}
private void thread2()
{
foreach(mystack.Children中的UserControl1控件)
{
}
//////或
对于(i=o;i如果做一些反射:
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获取实例的运行时类型。使用type方法按其类型筛选子项
foreach (UserControl1 control in mystack.Children.OfType<UserControl1>())
{
}
foreach(mystack.Children.OfType()中的UserControl1控件)
{
}
在我尝试之前,再看看我的帖子,按照你的逻辑,应该foreach(mystack.Children中的UserControl1控件)
做同样的事情吗?即使这样也只能得到UserControl1
s,对吗?无论如何,我会给你的解决方案一个尝试等待…我在你的答案中没有看到任何循环???我需要循环控制,我在帖子中提到clearlytypeof(InstanceFobjecthere)不会编译这是非常错误的:(…请不要给出误导性的答案:)我忘了给出一个严格的答案…我应该使用foreach并将所有选项放在那里。我刚才说…使用与Eugene Did相同的反射,但在我的循环foreach中(mystack.Children中的UserControl1控件)
它不是自动获取类型吗?是的。OfType过滤掉所有在OfType上的控件UserControl1@user9530640抱歉,我误解了您的问题。如果您执行foreach(mystack.Children中的UserControl1控件)
并且一些子项不是UserControl1类型,那么将出现一些异常,可能是强制转换异常或类似异常