【问题标题】:ImageSource Binding Slow for Normal Sized Image using C# and XAML in WPF/MVVM在 WPF/MVVM 中使用 C# 和 XAML 的正常大小图像的 ImageSource 绑定速度慢
【发布时间】:2015-04-16 22:24:14
【问题描述】:

我对 MVVM 和数据绑定还是很陌生。我有一个 GUI,可以根据用户在组合框中选择的内容来更改图像。问题是图像需要更改时会出现短暂的延迟。滞后冻结了 GUI,然后图像出现并且一切正常。即使图像加载缓慢,我也希望 GUI 不会冻结。

该图像不像其他人所询问的那样是缩略图,并且那里发布了解决方案。它是 .png,最大的文件约为 17K。考虑到图像的大小,这似乎应该很快。

我尝试过使用不同的线程,但我认为问题出在 Image.Source 中。我不确定如何在单独的线程上运行 xaml,但这是我试图解决这个问题的蛮力尝试。

任何帮助将不胜感激。提前致谢!

这是 xaml:

<!-- Image -->
<Grid Grid.Column="1" Grid.Row="0" 
       Grid.RowSpan="10"
       Margin="40,40,40,0"
       Width="Auto"
        >
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>
    <Image Grid.Column="0" Grid.Row="0"
        Height="Auto"
        Source="{Binding Path=ProfileImage}"
        Stretch="UniformToFill"
        Width="Auto"
       />
    <Label Grid.Column="0" Grid.Row="1"
        Content="{Binding Path=Profile}"
        Height="{Binding Path=ProfileCaptionHeight}"
        HorizontalAlignment="Center"
        HorizontalContentAlignment="Center"
        VerticalAlignment="Bottom"
        VerticalContentAlignment="Bottom"
        />
</Grid>

这是绑定的属性:

public string ProfileImage
{
    get
    {
        if (this.ProfileImageShown)
        {
            return _profileImage;
        }
        return null;
    }
    set
    {
        _profileImage = value;

        if (value != null)
        {
            this.ProfileImageShown = true;
        }
        else
        {
            this.ProfileImageShown = false;
        }
        base.OnPropertyChanged("ProfileImage");
    }
}

其中 _profileImage 是图像的完整路径。

【问题讨论】:

  • 您正在加载的图像的像素删除是多少?如果它们是非常大的图像(宽度 * 高度)。这可能是原因。
  • 最大的图片真的是17K吗?这没什么,它应该在没有任何明显延迟的情况下加载。您的应用程序可能还有其他问题。请注意,在您的 ProfileImage 属性中,getter 和 setter 不一致,即 getter 不会返回您作为参数传递给 setter 的内容。这是不好的做法,应该避免。想象一下如果你打电话给this.ProfileImage = this.ProfileImage; 会发生什么
  • @steveybrown:像素尺寸为 729x444
  • @Clemens:我也在想同样的事情,17K 什么都不是。那么可能导致延迟的原因是什么?感谢您指出 getter/setter 不一致。我没有想过那种场景。一点一点我会变得更好!
  • 在 Windows 资源管理器中查看最大图像属性时,它显示图像为 16.4KB,但磁盘大小为 20.0KB。我想知道如果总像素数为 323,676,这怎么可能?无论哪种方式,它都是一个非常小的图像,并且应该加载得如此之快以至于不会引起注意。

标签: c# wpf xaml mvvm imagesource


【解决方案1】:

您可以尝试将 IsAsync=true 添加到您的绑定中。这至少应该阻止它锁定你的用户界面。如上所述,无论如何它应该很快,所以可能还有其他事情发生。

            <Image Grid.Column="0" Grid.Row="0"
                Height="Auto"
                Source="{Binding Path=ProfileImage, IsAsync=True}"
                Stretch="UniformToFill"
                Width="Auto"
               />

【讨论】:

  • 感谢您的提示。你是对的,一定有其他事情发生,因为我没有注意到滞后的任何变化。一旦我弄清楚了,我会告诉你的。
  • 有了这个用户至少不必等待。但是图像仍然会出现巨大的延迟,并且在某些情况下可能会导致错误信息。
猜你喜欢
  • 2018-07-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多