【问题标题】:binding device image path windows phone 8.1绑定设备图片路径 windows phone 8.1
【发布时间】:2014-10-02 05:11:24
【问题描述】:

windows phone如何绑定设备图片路径

下面是图片路径

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

谢谢

【问题讨论】:

    标签: windows-phone-8.1


    【解决方案1】:

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

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

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-12
      • 2015-08-25
      • 2014-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多