简体   繁体   English

使用绑定转换器在WPF中异步加载图像

[英]Loading image asynchronously in WPF using binding converter

I have a Image control with binding settings like this: 我有一个具有绑定设置的Image控件,如下所示:

<Image Stretch="Uniform" Source="{Binding Path=CurrentItem, Converter={StaticResource ImgConverter}, IsAsync=True}"/>

And the ImgConverter is: ImgConverter是:

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            string uri = null;

            Compressor.Unzip((value as Zipfile));

            uri = string.Format("{0}{1}.jpg", Compressor.TempPath, value.ToString());

            return uri;

        }

The Compressor.Unzip(...) method does take some time. Compressor.Unzip(...)方法确实需要一些时间。 I set the binding IsAsync=True but it doesn't work(NOT on converter but only on path?). 我设置了绑定IsAsync=True但是它不起作用(不是在转换器上而是仅在路径上?)。 How can I handle this asynchronously? 我该如何异步处理?

Add a readonly Image property to your Zipfile class, and move the converter code to the property getter: 在您的Zipfile类中添加一个只读Image属性,并将转换器代码移至属性getter:

public class Zipfile
{
    ...

    public ImageSource Image
    {
        get
        {
            Compressor.Unzip(this);
            var uri = string.Format("{0}{1}.jpg", Compressor.TempPath, this.ToString());
            return new BitmapImage(new Uri(uri));
        }
    }
}

Then write your binding like this: 然后像这样写你的绑定:

<Image Source="{Binding Path=CurrentItem.Image, IsAsync=True}"/>

Using Multibinding with two binding, First is self image control and second is your current binding, in converter you can call async your method to unzip the file and in callback you can set image path(refer to first binding); Multibinding与两个绑定一起使用,第一个是自我图像控制,第二个是您当前的绑定,在转换器中,您可以调用async您的方法来解压缩文件,而在回调中,您可以设置图像路径(请参阅第一个绑定); Also you can see this sample: 您还可以看到以下示例:

http://social.msdn.microsoft.com/Forums/en-US/7fc238ea-194e-4f29-bcbd-9a3d4bdb2180/async-loading-of-bitmapsource-in-value-converter?forum=wpf http://social.msdn.microsoft.com/Forums/en-US/7fc238ea-194e-4f29-bcbd-9a3d4bdb2180/async-loading-of-bitmapsource-in-value-converter?forum=wpf

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM