我创建了一个包含多个控件的页面,在此我必须获取页面中的图像。我将图像名称作为字符串值。我做了一个 for 循环来查找图像并返回,但是如果循环页面中的所有控件如果它更多并且它也需要很多时间,那么它是乏味的。
// 传递字符串并查找为图像
Image imgBack = FindControl<Image>((UIElement)Layout, typeof(Image), strSelectedimg);
// 查找图片的函数
public T FindControl<T>(UIElement parent, Type targetType, string ControlName) where T : FrameworkElement
{
if (parent == null) return null;
if (parent.GetType() == targetType && ((T)parent).Name == ControlName)
{
return (T)parent;
}
T result = null;
int count = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < count; i++)
{
UIElement child = (UIElement)VisualTreeHelper.GetChild(parent, i);
if (FindControl<T>(child, targetType, ControlName) != null)
{
result = FindControl<T>(child, targetType, ControlName);
break;
}
}
return result;
}
有没有其他简单的方法可以使用字符串值在页面中查找图像。?