【问题标题】:Calling the Convert method from Converter just once for each item in ItemsControl对 ItemsControl 中的每个项目仅从 Converter 调用 Convert 方法一次
【发布时间】:2014-10-21 02:24:13
【问题描述】:

我有一个 ItemsControl 控件。在它的项目中,我展示了很多东西:每个项目中有两个图像,一些文本块等。

每件商品中显示的一张图片对于所有商品都是相同的。它位于我项目的 Resources.resx 文件中,这是我加载它的方式:

<Image Width="60" Height="60" VerticalAlignment="Center" HorizontalAlignment="Center" Grid.Row="0" Grid.Column="2" Grid.RowSpan="2">
    <Image.Source>
        <Binding Source="{x:Static properties:Resources.myImageName}" Converter="{StaticResource BitmapToImageConverter}" />
    </Image.Source>
</Image>

我的 BitmapToImageConverter 转换器类的 Convert 方法如下所示:

public object Convert(object value, Type targetType, object parameter,
        System.Globalization.CultureInfo culture)
    {
        using (MemoryStream stream = new MemoryStream())
        {
            ((System.Drawing.Bitmap)value).Save(stream, ImageFormat.Png); 

            stream.Position = 0;
            BitmapImage resultImage = new BitmapImage();
            resultImage.BeginInit();                
            resultImage.CacheOption = BitmapCacheOption.OnLoad;
            resultImage.StreamSource = stream;
            resultImage.EndInit();
            resultImage.Freeze();
            return resultImage;
        }
    }

现在,绑定需要很多时间,我想以某种方式缩短它。为我的 itemscontrol 中的每个项目调用一次 Convert 方法,但使用相同的图像(相同的参数)。我怎样才能为所有项目只调用一次?

转换器扩展了 IValueConverter 类。

【问题讨论】:

    标签: wpf image converter itemscontrol


    【解决方案1】:

    如果我没有误解你的问题,试试这个

    public class ImageConverter : ValueConverter
    {
        static BitmapImage resultImage = null;
        public object Convert(object value, Type targetType, object parameter,
        System.Globalization.CultureInfo culture)
        {
            if (resultImage != null)
                return resultImage;
            using (MemoryStream stream = new MemoryStream())
            {
                ((System.Drawing.Bitmap)value).Save(stream, ImageFormat.Png);
    
                stream.Position = 0;
                resultImage = new BitmapImage();
                resultImage.BeginInit();
                resultImage.CacheOption = BitmapCacheOption.OnLoad;
                resultImage.StreamSource = stream;
                resultImage.EndInit();
                resultImage.Freeze();
                return resultImage;
            }
        }
    

    创建一个静态变量,第一次赋值,下次返回

    【讨论】:

      猜你喜欢
      • 2011-04-03
      • 1970-01-01
      • 2011-10-08
      • 2023-03-06
      • 2018-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-29
      相关资源
      最近更新 更多