使用字符串访问图像类型

Access Image type using string

所以我有 i 张图片,我在代码中设置了图片名称,例如

image.Name = "Image" + i;

我想访问所有 i 图像,以便我可以更改其 属性 并绑定它。我使用此代码:

for (int i = 1; i < itotal; i++)
{
    Binding binding = new Binding
    {
        Source = AtextBox,
        Path = new PropertyPath("Text"),
    };
    Image imagex = (Image)this.FindName("Image" + i);
    xImage = imagex;
    xImage.SetBinding(ContentControl.OpacityProperty, binding);
}

但是我无法获取imagex,它的值保持为空。为什么?正确的做法是什么?

您正在尝试将元素添加到已解析的元素树中。为此,您需要 你需要打电话给 RegisterName.

// ...
image.Name = "Image" + i;
this.RegisterName(image.Name, image);

// ...

for (int i = 1; i < itotal; i++)
{
    Binding binding = new Binding
    {
        Source = AtextBox,
        Path = new PropertyPath("Text"),
    };
    Image imagex = (Image)this.FindName("Image" + i);
    xImage = imagex;
    xImage.SetBinding(ContentControl.OpacityProperty, binding);
}