【问题标题】:Binding Image Source to Page将图像源绑定到页面
【发布时间】:2015-12-11 01:03:09
【问题描述】:

我正在尝试让图像出现在 UWP 应用中的图像内,以便我可以从图像选择器向最终用户显示所选图像。我可以根据用户通过文件选择器选择图像来判断当前文件正在正确设置,但表单上没有显示任何内容。有人可以帮忙吗?

MainPage.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);
        }
    }

【问题讨论】:

  • 您将需要一个转换器,并且可能很少使用异步。 this answer 有可能对您有所帮助。

标签: c# xaml windows-store-apps uwp


【解决方案1】:

您可以使用问题评论中提到的绑定转换器,或者将视图模型属性的类型更改为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;
}

【讨论】:

    【解决方案2】:

    这里的问题是,类型StorageFile不能转换为 图像的来源。因此您必须使用ValueConverter 或 将类型StorageFile更改为Image

    所以属性将如下所示:

    private Image _CurrentFile;    
    public Image CurrentFile
    {
        get
        {
           return _CurrentFile;
        }
    }
    

    ImageSystem.Windows.Controls 命名空间下

    【讨论】:

    • 我打错了,“不匹配”,评论不能编辑,所以删除。
    【解决方案3】:

    根据@Clemens,我必须将属性的类型更改为图像源,然后在 UI 线程上异步加载它以获取要显示的图像。

    在这种情况下,对于任何尝试将图像加载为 WPF Image 类型的源的人的答案是:

    通过您的 StorageFile 设置方法中的 UI Dispatcher 运行它:

    //Acquire storagefile via a picker or something
    public StorageFile CurrentFile
    {
        get { return currentImage; }
        set {
            SetValue(ref currentImage, value); 
            CoreWindow.GetForCurrentThread().Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => SetCurrentImageAsync(value));
        }
    }
    

    将图像异步加载到 CurrentImage 属性

    public ImageSource CurrentImage
    {
        get { return currentImage; }
        set { SetValue(ref currentImage, value); }
    }
    
    public async Task SetCurrentImageAsync(StorageFile file) {
        var bitmap = new BitmapImage();
        await bitmap.SetSourceAsync(await file.OpenReadAsync());
        this.CurrentImage = bitmap;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-03-29
      • 1970-01-01
      • 2014-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-26
      相关资源
      最近更新 更多