添加对数组引用的一系列图像



我正在研究现有的UWP(通用Windows平台(,我有以下代码,

UWP:

<Image x:Name="img1" ... />
.
.
<Image x:Name="img100" ... />

C#:

private BitmapImage empty = new BitmapImage(new Uri(@"C:\imgempty.png"));
private void Init()
{
img1.Source = e;
.
.
img100.Source = e;
}

它有效。但是我想进行一些重构,以便我可以将其放在图像对象数组中,例如:

var imageInitList = new Image[100];
imageInitList[0] = img1;
.
.
imageInitList[99] = img100;

问题,如何在 C# 中应用以下 psudo? img1 ...img100 是图像类型。

for (int i = 0; i < length; i++)
{
imageInitList[i] = img + i
}

在 XAML 中声明大量Image元素听起来像是更适合代码隐藏文件或布局控件(如GridViewListView(的工作。但是,如果坚持将声明保留在 XAML 中,则可以使用FindName方法查询x:Name

for (int i = 0; i < length; i++)
{
imageInitList[i] = (Image)FindName($"img{i}");
}

FindNameFrameworkElement上的一个方法,因此您可以在页面的代码隐藏中调用它以获取页面中的任何命名元素。

最新更新