简体   繁体   中英

How to set local downloaded image to BitmapImage?

I have downloaded image, class and listview with Image Control This is class which I bind to my listview:

class MagazineDownload
    {
        public string Title { get; set; }
        public string Date { get; set; }
        public BitmapImage Cover { get; set; }
        public string Pdf { get; set; }

        public MagazineDownload(string title, string image, string date, string pdf)
        {
            Title = title;
            Cover = new BitmapImage();
            addImage(image);
            Date = date;
            Pdf = pdf;
        }


        private async void addImage(string image)
        {
            StorageFile storageFile = await ApplicationData.Current.LocalFolder.GetFileAsync(image);
            IAsyncOperation<IRandomAccessStream> operation = storageFile.OpenAsync(FileAccessMode.Read);
            IRandomAccessStream stream = await operation;
            Cover.SetSource(stream);      
        }
    }

This is code for image binding:

<ListView
                    Margin="19,-23,-19.167,23.333"
                    AutomationProperties.AutomationId="PivotListViewSection"
                    SelectionMode="None"
                    IsItemClickEnabled="False"
                    ItemClick="downList_ItemClick"
                    ItemsSource="{Binding}"
                    x:Uid="downList"
                    x:Name="downList"
                    >
                    <ListView.ItemTemplate>
                        <DataTemplate>
                            <StackPanel Orientation="Horizontal">
                                <Image x:Name="imageDownCover" Height="100" Width="100" Stretch="Fill" Source="{Binding Cover}"/>

Everything (Title, date, pdf button tag) works except the image.

How to fix it?

Avoid calling any async methods from a constructor. It will be set, but it needs to notify the UI via INotifyPropertyChanged.

Since the image is a local file, you can use the local folder uri and just set the uri in the constructor.

public MagazineDownload(string title, string image, string date, string pdf)
{
    //don't forget the triple forward slashes
    var uri = string.Format("ms-appdata:///local/{0}", image);

    Title = title;
    Cover = new BitmapImage(new Uri(uri));
    Date = date;
    Pdf = pdf;
}

I recommend setting up INotifyPropertyChanged since all your properties are public get and set, you'll want your UI to update if any of these values change. If they shouldn't change, make them have a private readonly backing variable so nothing can change them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM