c# - 将图像源绑定(bind)到页面

标签 c# xaml windows-store-apps uwp

我正在尝试让图像出现在 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/

相关文章:

c# - Autofixture - 创建带余数的 float 、 double 或小数

c# - 像向导一样的 MVVM

c# - 在C#中设置按钮图标

javascript - 使用 localStorage 的 Jquery 自动登录

wpf - 动态资源合并不将样式应用于第一个控件

c# - Android 上的 Xamarin.Forms TapRecognizer 取消 ItemTapped 事件

c# - Windows 10 UWP - 检测当前的互联网连接是 Wifi 还是蜂窝网络?

forms-authentication - 如何在 Windows Store App 中使用 HttpClient 登录 ASP.Net MVC 网站(表单例份验证)?

multithreading - 为什么不能在WinRT(Windows Store App)中阻止主线程?

c# - 使用 C# 在 Powerpoint 2013 中创建具有多个系列的图表