binding device image path windows phone 8.1

2020-02-15 15:20发布

How to bind device image path windows phone.

Below is image path

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

Thanks

1条回答
家丑人穷心不美
2楼-- · 2020-02-15 15:50

I'm not sure if in your case using string is a good choice - maybe it will be possible to use BitmapImage - obtain a StorageFile from path, open Stream and then set BitmapImage - in this case you perform async operations outside converter.

In case you still want to use string it's possible, but will need some special approach - using async methods along with binding. There is a very good article about aynchronous MVVM, written by Stephen Cleary. Basing on the article and other Stephen's answer I've made such a code:

First of all, we will have to define a Converter - it's little complicated as getting file and stream is asynchronous:

/// <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;
        }
    }
}

In our page we will need a property, which we will use in binding and set the 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

Of course we have to define our binding - for example in XAML, it's little tricky as first we have to bind the DataContext to our Task then bind Source to the Result, which will be raised as the image is loaded:

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

Once we have this all, we can set the property like this:

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

and we should see the result on the screen.

查看更多
登录 后发表回答