C# 在 WPF 中循环遍历 StackPanel 子项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17990735/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Looping through StackPanel children in WPF
提问by user1590636
I have a StackPanel
that is full of controls, I am trying to loop through the elements and get their Names, but it seems that I need to cast each element to its type in order to access its Name
property.
我有一个StackPanel
充满控件的控件,我试图遍历元素并获取它们的名称,但似乎我需要将每个元素转换为其类型才能访问其Name
属性。
But what if I have a lot of different types in the StackPanel and I just want to get the elements name?
但是如果我在 StackPanel 中有很多不同的类型并且我只想获取元素名称怎么办?
Is there a better way to do that?
有没有更好的方法来做到这一点?
Here is what I've tried:
这是我尝试过的:
foreach (object child in tab.Children)
{
UnregisterName(child.Name);
}
采纳答案by Henk Holterman
It should be enough to cast to the right base class.
Everything that descends from FrameworkElement
has a Name property.
转换到正确的基类应该足够了。所有的后代FrameworkElement
都有一个 Name 属性。
foreach(object child in tab.Children)
{
string childname = null;
if (child is FrameworkElement )
{
childname = (child as FrameworkElement).Name;
}
if (childname != null)
...
}
回答by Clemens
You may just use the appropriate type for the foreach loop variable:
您可以只为 foreach 循环变量使用适当的类型:
foreach (FrameworkElement element in panel.Children)
{
var name = element.Name;
}
This works as long as there are only FrameworkElement
derived controls in the Panel. If there are also others (like derived from UIElement
only) you may write this:
只要FrameworkElement
Panel中只有派生控件,这就会起作用。如果还有其他人(例如UIElement
仅派生自),您可以这样写:
using System.Linq;
...
foreach (var element in panel.Children.OfType<FrameworkElement>())
{
var name = element.Name;
}
回答by Marc
Using LINQ:
使用 LINQ:
foreach(var child in tab.Children.OfType<Control>)
{
UnregisterName(child.Name);
}