我试图按类型和标签名称检索所有元素。我已经找到了一些例子:
How can I find WPF controls by name or type?
https://stackoverflow.com/a/978352/7444801
我试图修改其中的一些例子但是,他们从来没有给我我想要的结果。
所需方法的示例:
public static Collection<T> FindAll<T>(DependencyObject parent, string childName)
where T : DependencyObject
{
//code that gives me the collection
}
示例所需的标记对象:
<Ellipse Tag="tagname" Fill="Blue" Width="25" Height="25" />
<Ellipse Tag="tagname" Fill="Blue" Width="25" Height="25" />
<Ellipse Tag="tagname" Fill="Blue" Width="25" Height="25" />
我试过的方法:
public static Collection<T> FindAll<T>(DependencyObject parent, string childName)
where T : DependencyObject
{
Collection<T> result=null;
Boolean b = true;
int c = 0;
while (b)
{
T obj = FindChild<T>(parent, childName, c,-1);
if (obj == null) b = false;
else
{
if(result == null) result = new Collection<T>();
result.Add(obj);
}
c++;
}
return result;
}`
` /**
* Param c = count of desired object
* Param indchild= keeps cound (give negative for calling function)
* */
public static T FindChild<T>(DependencyObject parent, string childName,int c, int indchild)
where T : DependencyObject
{
// Confirm parent and childName are valid.
if (parent == null) return null;
T foundChild = null;
int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
if(indchild<=-1)indchild = 0;
for (int i = 0; i < childrenCount; i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
// If the child is not of the request child type child
T childType = child as T;
if (childType == null)
{
// recursively drill down the tree
foundChild = FindChild<T>(child, childName,c,indchild);
// If the child is found, break so we do not overwrite the found child.
if (foundChild != null) break;
}
else if (!string.IsNullOrEmpty(childName))
{
var frameworkElement = child as FrameworkElement;
// If the child's name is set for search
if (frameworkElement != null && frameworkElement.Tag!=null && ((String)frameworkElement.Tag).Equals(childName))
{
// if the child's name is of the request name
if (c == indchild) {
foundChild = (T)child;
break;
}
indchild++;
}
}
}
return foundChild;
}
答案 0 :(得分:3)
您可以使用以下string tagName = "tagname";
IEnumerable<Ellipse> elements = FindVisualChildren<Ellipse>(this).Where(x => x.Tag != null && x.Tag.ToString() == tagName);
方法:
Find all controls in WPF Window by type
...只需过滤结果:
static_pages_controller_test.rb
答案 1 :(得分:0)
尝试了社区推荐的许多解决方案。没有一个真正有效。不得不修改一下。这是对我有用的。
List<LayoutPanel> panels = new List<LayoutPanel>();
foreach (object rawChild in LogicalTreeHelper.GetChildren(dockManager))
{
if (rawChild is DependencyObject)
{
DependencyObject child = (DependencyObject)rawChild;
if (child is LayoutPanel)
{
panels.Add((LayoutPanel)child);
}
foreach (LayoutPanel childOfChild in FindLogicalChildren<LayoutPanel>(child))
{
panels.Add(childOfChild);
}
}
}
var requiredPanel = panels.Where(t => t.Tag.ToString() == tagName).FirstOrDefault();