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

Mat*_*t.M 2 c# silverlight isolatedstorage windows-phone-7

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

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

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

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

Mat*_*cey 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(@"\", "/") #>",
<#              }
            }
#>
                        };
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

它会产生类似的东西:

// <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",
                        };
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

  • 在对T4模板进行了一些通知后,这完全奏效了.谢啦.http://msdn.microsoft.com/en-us/library/gg251242.aspx (2认同)