1

我创建了一个包含多个控件的页面,在此我必须获取页面中的图像。我将图像名称作为字符串值。我做了一个 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;
     }     

有没有其他简单的方法可以使用字符串值在页面中查找图像。?

4

2 回答 2

0

如果您使用 Silverlight Toolkit,那么您不需要自己维护这个帮助器方法,因为它已经提供了一个类似的扩展方法。

using System.Linq;
using System.Windows.Controls.Primitives;

// ...

private void DoStuff()
{
    var myImage = this.MyRootLayoutPanel.GetVisualDescendants().OfType<Image>()
        .Where(img => img.Name == "MyImageName").FirstOrDefault();
}

或者,我不知道你的确切情况,但如果你正在制作一个正确的模板Control而不是一个简单的UserControlor Page,你就这样做

public class MyFancyControl : Control
{
    public MyFancyControl()
    {
        this.DefaultStyleKey = typeof(MyFancyControl);
    }

    // ...

    public override void OnApplyTemplate()
    {
        var myImage = this.GetTemplateChild("MyImageName") as Image;
    }
}
于 2012-09-21T17:10:36.827 回答
0

也许您可以在添加图像的同时构建查找。如果您发布在运行时添加图像的代码,我可以给您更准确的答案;但我在想这样的事情:

private Dictionary<string, Image> _imageLookup;

private class ImageInfo
{
    public string Name { get; set; }
    public string Uri { get; set; }
}

private void AddImages(ImageInfo[] imageInfos)
{
    this._imageLookup = new Dictionary<string, Image>();
    foreach (var info in imageInfos)
    {
        var img = CreateImage(info.Name, info.Uri);
        if (!this._imageLookup.ContainsKey(info.Name))
        {
            this._imageLookup.Add(info.Name, img);
        }
        AddImageToUI(img);
    }
}

private Image CreateImage(string name, string uri)
{
    // TODO: Implement
    throw new NotImplementedException();
}

private void AddImageToUI(Image img)
{
    // TODO: Implement
    throw new NotImplementedException();
}

然后您可以稍后轻松找到该图像:

public Image FindControl(string strSelectedImg)
{
    if (this._imageLookup.ContainsKey(strSelectedImg))
    {
        return this._imageLookup[strSelectedImg];
    }
    else
    {
        return null; // Or maybe throw exception
    }
}

如果您需要查找的不仅仅是图像,您可以使用Dictionary<string, Control>orDictionary<string, UIElement>代替。

于 2012-09-21T16:45:57.387 回答