【问题标题】:Why is my ImageSource Binding not updated?为什么我的 ImageSource 绑定没有更新?
【发布时间】:2018-01-31 21:03:37
【问题描述】:

我正在尝试将 XAML 中的图像源动态绑定到 ViewModel (MVVM) 中的 URI。这适用于初始 URI,显示图片“C:\tmp\Test.png”。但是,如果我在ViewModel 中将另一个URI 设置为ImageURI,则图片不会更新。谁能帮帮我?

XAML:

<Image x:Name="UserImage" Stretch="Fill" Grid.Row="0">
    <Image.Source>
        <BitmapImage CreateOptions="IgnoreImageCache" UriSource="{Binding ImageURI, UpdateSourceTrigger=Explicit, Mode=TwoWay}"/>
    </Image.Source>
</Image>

视图模型:

public string imageURI = "C:\\tmp\\Test.png";
public string ImageURI
{
    get
    {
        return imageURI;
    }
    set
    {
        imageURI = value;
        this.OnPropertyChanged("ImageURI");
    }
}

【问题讨论】:

    标签: wpf image xaml mvvm


    【解决方案1】:

    BitmapImage 实现 ISupportInitialize。这意味着初始化后忽略属性更改。更改 Binding 的源属性无效。

    您应该直接绑定 Image 的 Source 属性。内置的自动类型转换将在后台创建一个 BitmapFrame。

    <Image Source="{Binding ImageURI}" .../>
    

    在 Binding 上设置 UpdateSourceTrigger=ExplicitMode=TwoWay 是没有意义的。

    如果您需要显式创建 BitmapImage(例如设置了 IgnoreImageCache 选项的图像),请编写适当的 Binding Converter。

    【讨论】:

    • 谢谢!但不幸的是,一切都没有改变。图像在程序启动时加载一次,但在此之后图像保持原样。当我调试时,我可以看到 OnPropertyChanged 的​​处理程序为空: protected void OnPropertyChanged(string name) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(name)); } } 问题可能是什么?
    • 您可能忘记了 ViewModel 类声明中的 INotifyPropertyChanged 接口吗?
    • 不,我没有。我的 ViewModel 中的其他绑定可以正常工作。当我在更新后的代码中设置 Image.Source 时。但我不想打破 MVVM 模式。
    • 新的ImageURI是另一个绝对路径?
    • 是的。嗯?没有在网上找到一些工作代码。不敢相信 WPF 不支持这样的基本功能...
    【解决方案2】:

    这里很老的问题没有解决方案。太好了,因为我遇到了类似的问题并使用了稍微不同的方法,所以这是我的解决方案:

    使用以这种方式返回 BitmapImage 的转换器:

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
        BitmapImage error = new();
        error.BeginInit();
        // OnLoad will give you errors just with the start of your application and 
        // and won't hide somewhere in your log
        error.CacheOption = BitmapCacheOption.OnLoad;
        error.UriSource = new Uri(@"pack://application:,,,/Images/error.png");
        error.EndInit();
        error.Freeze();
    
        return error;
    }
    

    绑定:

    <Image Source="{Binding Status, Converter={StaticResource enumAnalyzerStatusConverter}, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}" />
    

    OnLoad 选项将在启动时出现错误,如果您的图像出现问题,例如路径。记得在项目资源管理器中将图片设置为Ressource

    【讨论】:

      猜你喜欢
      • 2020-04-21
      • 2021-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-11
      相关资源
      最近更新 更多