Loading image from projects files

空扰寡人 提交于 2019-12-10 22:29:17

问题


I'm trying to get png image which is my Resource folder. I tested solution that was written here :Add images to ListBox (c#, windows phone 7). For start I wanted to get the same image for every item in my ListBox. But I can't achive that. The picture doesn't show.

It's how my list in xaml look like:

<ListBox x:Name="ProductList">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel>
                        <TextBlock Text="{Binding Name}"/>
                        <Image Source="{Binding ImagePath}"  Stretch="None"/>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

This is how I populate Items:

List<ImageData1> productsList = new List<ImageData1>();

foreach (ProductItem item in ProductsTable)
{
    if (item.Category == chosenCategory.TrId)
    {
            ImageData1 img = new ImageData1();
            img.Name = item.Name;
            img.ImagePath = new Uri("Resources/img.png", UriKind.RelativeOrAbsolute);
            productsList.Add(img);
    }
}

ProductList.ItemsSource = productsList;

Here is my class to hold image data:

public class ImageData1
{
    public Uri ImagePath
    {
        get;
        set;
    }

    public string Name
    {
        get;
        set;
    }
}

回答1:


Try putting / before your image path. Like /Resources/img.png. And try to change UriKind.RelativeOrAbsolute to UriKind.Relative. And make sure your images are added as Content (Build Action property of image). That way it works for me.




回答2:


Probably, You can also use the following assembled code to read the image from the current application.

StreamResourceInfo info =Application.GetResourceStream(new Uri("Resources/img.png", UriKind.RelativeOrAbsolute));
var bitmap = new BitmapImage();
bitmap.SetSource(info.Stream);
img.Soure = bitmap;


来源:https://stackoverflow.com/questions/14628416/loading-image-from-projects-files

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