Dynamically load images from project folder - Windows Phone 7

强颜欢笑 提交于 2019-12-11 00:33:34

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!