绑定设备图像路径Windows Phone 8.1

时间:2014-10-01 10:33:53

标签: windows-phone-8.1

如何绑定设备图像路径窗口手机。

以下是图片路径

"C://Data//Users//Public//Pictures//Camera Roll//WP_20141001_002.jpg"

由于

1 个答案:

答案 0 :(得分:3)

我不确定在您的情况下使用 string 是否是一个不错的选择 - 也许可以使用 BitmapImage - 获取 StorageFile from path,打开 Stream ,然后设置 BitmapImage - 在这种情况下,您可以在转换器外执行 async 操作。

如果您仍想使用 string ,则可能需要一些特殊方法 - 使用 async 方法和绑定。关于异步MVVM的There is a very good article,由Stephen Cleary编写。基于文章和other Stephen's answer我已经制作了这样的代码:

首先,我们必须定义一个 Converter - 它有点复杂,因为获取文件和流是异步的:

/// <summary>
/// Converter getting an image basing upon delivered path
/// </summary>
public class PathToImage : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        var task = GetImage((String)value);
        // the below class you will find in Stephen's answer mentioned above
        return new TaskCompletionNotifier<BitmapImage>(task);
    }

    public object ConvertBack(object value, Type targetType, object parameter, string language)
    { throw new NotImplementedException(); }

    private async Task<BitmapImage> GetImage(string path)
    {
        StorageFile file = await StorageFile.GetFileFromPathAsync(path);
        using (var stream = await file.OpenAsync(FileAccessMode.Read))
        {
            BitmapImage image = new BitmapImage();
            image.SetSource(stream);
            return image;
        }
    }
}

在我们的页面中,我们需要一个属性,我们将在绑定中使用它并设置DataContext:

public sealed partial class MainPage : Page, INotifyPropertyChanged
{
    private string imagePath;
    public string ImagePath
    {
        get { return imagePath; }
        set { imagePath = value; RaiseProperty("ImagePath"); }
    }

    public MainPage()
    {
        this.InitializeComponent();
        DataContext = this;
    }
    // rest of the code

当然我们必须定义我们的绑定 - 例如在XAML中,它有点棘手,因为首先我们必须将DataContext绑定到我们的Task然后将Source绑定到Result,这将在加载图像时引发:

<Image DataContext="{Binding ImagePath, Converter={StaticResource PathToImage}}" Stretch="Uniform"
       Source="{Binding Result} HorizontalAlignment="Stretch" VerticalAlignment="Stretch"/>

一旦我们拥有了这一切,我们可以像这样设置属性:

ImagePath = @"C:\Data\Users\Public\Pictures\Camera Roll\WP_20141001_002.jpg";

我们应该在屏幕上看到结果。

相关问题