简体   繁体   中英

Binding Image from FilePicker and project folder in ViewModel

I had a problem with displaying image that comes from 2 sources. I have a MainPage and MainPageViewModel. At first time when page loaded we get image from project folder using its Path. So in MainPage.xaml

<Image Source="{Binding ImageUri}" VerticalAlignment="Center" HorizontalAlignment="Center" Width="300" Height="300"/>

And MainPageViewModel

private string _imageUri;
public RelayCommand PickPhotoCommand { get; set; }
public string ImageUri
{
    get { return _imageUri; }
    set
    {
        _imageUri = value;
        NotifyPropertyChanged("ImageUri");
    }
}

Everything is clear and simple. But then User can pick image from filePicker and old image must be replaced with picked image. But we can't get Uri from StorageFile, that was returned by FilePicker and only option is get BitmapImage from StorageFile using SetSourceAsync() . I have two solutions that resolve my problem with displaying image on my xaml page. Thi first is - use BitmapImage for both sources, so for image from Project folder or somewhere else I can use

 ImageUri = new BitmapImage(new Uri("ms-appx:///Assets/StoreLogo.png"));

and change my ImageUri property type to BitmapImage. But my teamlead says that`s not good solution, cause BitmapImage used to change image(Scale, Crop etc.). So it is semantically incorrect. The second solution is - get file from FilePicker, copy it in Temprorary Folder and then get copiedFile from Folder and take it's path.

StorageFile file = await openPicker.PickSingleFileAsync();
StorageFolder tempFolder = ApplicationData.Current.TemporaryFolder;
StorageFile copiedFile = await file.CopyAsync(tempFolder, file.Name, NameCollisionOption.ReplaceExisting);
var fileFromTemp = await ApplicationData.Current.TemporaryFolder.GetFileAsync(copiedFile.Name);
ImageUri = fileFromTemp.Path;

And we can use string for our ImageUri property. Please give your feedback, which one of this solutions is best and more correct?

Change the type of your view model property to ImageSource , ie the type of the Image control's Source property.

private ImageSource image;
public ImageSource Image
{
    get { return image; }
    set
    {
        image = value;
        NotifyPropertyChanged("Image");
    }
}

Now you can easily assign a BitmapImage eg

viewModel.Image = new BitmapImage(new Uri("ms-appx:///Assets/StoreLogo.png"));

or

var bitmap = new BitmapImage();
using (var stream = await file.OpenReadAsync())
{
    await bitmap.SetSourceAsync(stream);
}
viewModel.Image = bitmap;

but also instances of other derived types, like WriteableBitmap .

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