问题
What I want to do seems very simple, and I've done it on other platforms...
Here some context: Lets say you have 1000 small images that you want to display in a databound ListBox. You start off by including the images in your project into the folder '/images'. You set their build action to 'Content'.
Now the question: How do you dynamically load all these images into your app at runtime? By dynamic, I mean without having to know each name of the 1000 images.
(In case you are thinking IsolatedStorage, I've tried that. The image folder is part of your project, but isn't automatically loaded into isolatedStorage, hence you cannot, as far as I know, load the images from IsolatedStorage)
回答1:
You can get this at design time with the following T4 template:
<#@ 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(@"\", "/") #>",
<# }
}
#>
};
}
}
}
It'll generate something like:
// <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",
};
}
}
}
You can obviously change the namespace and the name of the partial class as you se fit.
来源:https://stackoverflow.com/questions/6344865/dynamically-load-images-from-project-folder-windows-phone-7