从项目文件夹动态加载图像 - Windows Phone 7

时间:2011-06-14 14:10:30

标签: c# silverlight windows-phone-7 isolatedstorage

我想做的事情似乎非常简单,我已经在其他平台上完成了......

这里有一些上下文:假设您有1000个小图像要在数据绑定ListBox中显示。首先,将项目中的图像包含在“/ images”文件夹中。您将构建操作设置为“内容”。

现在的问题是:如何在运行时动态地将所有这些图像加载到您的应用中?通过动态,我的意思是不必知道1000个图像的每个名称。

(如果您正在考虑使用IsolatedStorage,我已经尝试过了。图像文件夹是项目的一部分,但不会自动加载到isolatedStorage中,因此,据我所知,您不能从IsolatedStorage加载图像)

1 个答案:

答案 0 :(得分:6)

您可以在设计时使用以下T4​​模板获取此信息:

<#@ template debug="false" hostspecific="true" language="C#" #>
<#@ output extension=".gen.cs" #>
<#@ import namespace="System.IO"#>
// <auto-generated />
using Microsoft.Phone.Controls;

namespace MyAppNamespace
{
    public partial class MainPage : PhoneApplicationPage
    {
        private static string[] AllFilesInImagesFolder()
        {
            return new[] {
<#
            DirectoryInfo directoryInfo = new DirectoryInfo(Path.Combine(Path.GetDirectoryName(Host.TemplateFile), "images"));

            foreach(FileInfo file in directoryInfo.GetFiles("*.*", SearchOption.AllDirectories))
            {
                if (!file.FullName.Contains(@"\."))
                {#>
                           "<#= file.FullName.Substring(file.FullName.IndexOf("images")).Replace(@"\", "/") #>",
<#              }
            }
#>
                        };
        }
    }
}

它会产生类似的东西:

// <auto-generated />
using Microsoft.Phone.Controls;

namespace MyAppNamespace
{
    public partial class MainPage : PhoneApplicationPage
    {
        private static string[] AllFilesInImagesFolder()
        {
            return new[] {
                           "images/image1.png",
                           "images/image2.png",
                           "images/image3.png",
                           "images/image4.png",
                           "images/image5.png",
                        };
        }
    }
}

显然,您可以根据需要更改命名空间和部分类的名称。