我正在尝试让图像出现在 UWP 应用程序的图像内部,以便我可以从图像选择器向最终用户显示所选图像。我可以根据用户通过文件选择器选择图像来正确设置当前文件,但表单上没有显示任何内容。谁能帮忙?
主页.xaml
<Border Grid.Row="1" BorderBrush="WhiteSmoke" BorderThickness="2" Margin="5">
<Image Source="{Binding CurrentFile}" Stretch="Fill" />
</Border>
MainPageViewModel.cs
public StorageFile CurrentFile {
get
{
return _currentFile;
}
set
{
SetValue(ref _currentFile, value);
}
}
最佳答案
您可以使用问题评论中提到的绑定(bind)转换器,或者将 View 模型属性的类型更改为 ImageSource
:
public ImageSource CurrentImage
{
get { return currentImage; }
set { SetValue(ref currentImage, value); }
}
然后您将从 StorageFile
创建一个 BitmapImage
并将其分配给如下属性:
var bitmap = new BitmapImage();
await bitmap.SetSourceAsync(await file.OpenReadAsync());
CurrentImage = bitmap;
当您在问题中提到“图像选择器”时,您可以像这样使用上面的代码:
var picker = new FileOpenPicker
{
SuggestedStartLocation = PickerLocationId.PicturesLibrary
};
picker.FileTypeFilter.Add(".jpg");
picker.FileTypeFilter.Add(".jpeg");
picker.FileTypeFilter.Add(".png");
var file = await picker.PickSingleFileAsync();
if (file != null)
{
var bitmap = new BitmapImage();
await bitmap.SetSourceAsync(await file.OpenReadAsync());
viewModel.CurrentImage = bitmap;
}
关于c# - 将图像源绑定(bind)到页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34214553/