从FilePicker绑定图像和ViewModel中的项目文件夹

时间:2016-12-15 16:23:24

标签: c# image xaml uwp

显示来自2个来源的图片时出现问题。我有一个MainPage和MainPageViewModel。在第一次加载页面时,我们使用其Path从项目文件夹中获取图像。 所以在MainPage.xaml

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

和MainPageViewModel

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

一切都清晰简单。但是,用户可以从filePicker中选择图像,旧图像必须替换为拾取的图像。但我们无法从StorageFile获取Uri,这是由FilePicker返回的,只有选项是使用SetSourceAsync()从StorageFile获取BitmapImage。我有两个解决方案,可以解决我在我的xaml页面上显示图像的问题。 首先是 - 对两个源使用BitmapImage,因此对于Project文件夹或其他地方的图像,我可以使用

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

并将我的ImageUri属性类型更改为BitmapImage。但是我的团队负责人说这不是一个好的解决方案,因为BitmapImage用来改变图像(Scale,Crop等)。所以它在语义上是不正确的。 第二个解决方案是 - 从FilePicker获取文件,将其复制到Temprorary文件夹中,然后从Folder获取replicationFile并获取它的路径。

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;

我们可以为ImageUri属性使用字符串。 请提供您的反馈,哪种解决方案最好,更正确?

1 个答案:

答案 0 :(得分:0)

将视图模型属性的类型更改为Source,即图像控件的private ImageSource image; public ImageSource Image { get { return image; } set { image = value; NotifyPropertyChanged("Image"); } } 属性的类型。

BitmapImage

现在您可以轻松指定viewModel.Image = new BitmapImage(new Uri("ms-appx:///Assets/StoreLogo.png")); 例如

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

WriteableBitmap

还有其他派生类型的实例,例如{{1}}。