You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用MVVM数据绑定绑定资源字典中的<DrawingImage>到ListBox项模板

实现方案

推荐采用资源Key+转换器的实现方式,是耦合度最低、最符合MVVM分层原则的方案,全程不需要ViewModel层引用任何WPF视图相关类型:

第一步:调整ViewModel定义

ImageToDisplay属性直接存储资源字典中对应图像的x:Key字符串即可,无需修改属性类型:

public class MyItemViewModel 
{
    public string TextToDisplay { get; set; }
    // 赋值为对应图像的资源Key即可,比如"MyDrawingImage"
    public string? ImageToDisplay { get; set; }            
}

第二步:实现资源查找转换器

新建转换器类,负责把传入的资源Key转换为对应的DrawingImage实例:

public class ResourceKeyToImageConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is not string resourceKey)
            return DependencyProperty.UnsetValue;
        // 全局查找已导入的资源,也可按需指定特定ResourceDictionary查找
        if (Application.Current.TryFindResource(resourceKey) is DrawingImage image)
            return image;
        return DependencyProperty.UnsetValue;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

第三步:修改XAML绑定逻辑

首先在页面/应用的资源区注册转换器:

<Window.Resources>
    <local:ResourceKeyToImageConverter x:Key="ResourceKeyToImageConverter"/>
</Window.Resources>

然后修改Image控件的绑定,指定转换器即可:

<Image Source="{Binding ImageToDisplay, Converter={StaticResource ResourceKeyToImageConverter}}" />

可选替代方案(不推荐)

如果不想额外写转换器,也可以直接把ImageToDisplay的属性类型改为ImageSource,在ViewModel层直接获取资源实例赋值给属性,但这种方式会让ViewModel依赖视图层的资源定义,耦合度更高,不符合纯MVVM设计规范。

内容的提问来源于stack exchange,提问作者user1573959

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 20:36:00