WPF按标签和类型查找所有控件 [英] Wpf find all Controls by tag and type
本文介绍了WPF按标签和类型查找所有控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试按类型和标记名称检索所有元素.我已经找到了一些例子:
I'm trying to retrieve of all elements by type and tag name. I already found some examples:
https://stackoverflow.com/a/978352/7444801
我试图修改其中一些示例,但是它们从未给我想要的结果.
I tried to modify some of those examples but, they never gave me the result I wanted.
所需方法的示例:
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;
}
推荐答案
您可以使用以下 FindVisualChildren
方法:
...并仅过滤结果:
...and simply filter the results:
string tagName = "tagname";
IEnumerable<Ellipse> elements = FindVisualChildren<Ellipse>(this).Where(x => x.Tag != null && x.Tag.ToString() == tagName);
这篇关于WPF按标签和类型查找所有控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文