更新时间:2022-06-22 02:16:16
这就是我所做的......
This is what I do...
构建操作
属性设置为资源
type。 ViewModel将图像名称保存在 string
中(比如属性 MyImageName
)当我绑定到的
XAML中的对象... 来源
时,我将其转换为相对路径
Images
in project's root folder. You can keep them in any assembly.Build Action
property set to Resource
type.The ViewModel holds image name in string
(say property MyImageName
) and I convert it as a relative path when bound to the Source
of Image
object in XAML...
public class ImagePathConverter
{
public void Convert(...)
{
return "pack://application:,,,/MyApplicationName;component/Images/" + value.ToString();
}
}
其中 MyApplicationName
是短程序集的名称,其下面有 Images
文件夹。
where MyApplicationName
is the short assembly's name that is having the Images
folder under it.
在XAML中,假设视图模型实例绑定到整个视图的数据上下文和/或至少与图像的数据相关.... / p>
In XAML, assuming the view model instance is bound to the data context of the entire view and / or atleast to the image's data contect ....
<Image Source="{Binding Path=MyImageName, Converter={StaticResource ImagePathConverter}}" />
但那是一个典型的方法通过MVVM引用WPF项目中的图像。其他方式包括加载Image的二进制流(来自 resx
或内容
类型图像或来自二进制数据库)。在这种情况下,您的转换器会将其转换为 BitMapImageSource
。
But then thats one of the typical ways to refer images in a WPF project via MVVM. Other ways include an Image's binary stream loaded (from resx
or Content
type images or from binary database). In such case your converter will convert it into a BitMapImageSource
.