我正在尝试按类型和标记名称检索所有元素。我已经找到了一些例子:
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;
}
最佳答案
您可以使用以下 FindVisualChildren
方法:
Find all controls in WPF Window by type
...并简单地过滤结果:
string tagName = "tagname";
IEnumerable<Ellipse> elements = FindVisualChildren<Ellipse>(this).Where(x => x.Tag != null && x.Tag.ToString() == tagName);
关于c# - Wpf 按标签和类型查找所有控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44138015/