【问题标题】:How to set image source in WPF programmatically [duplicate]如何以编程方式在WPF中设置图像源[重复]
【发布时间】:2020-04-01 10:21:54
【问题描述】:

我正在尝试在 WPF 中设置图像源,但相对 Uri 不起作用。

imgView.Source = new BitmapImage(new Uri("Res/Images/img.png", UriKind.Relative));

但这有效:

imgView.Source = new BitmapImage(new Uri("E:/C#/Folder/Project/Res/Images/img.png", UriKind.Absolute));

我应该在相对 Uri 中改变什么?

【问题讨论】:

  • 将镜像文件的Build Action设置为Resource。然后使用完整的资源文件Pack URI:imgView.Source = new BitmapImage(new Uri("pack://application:,,,/Res/Images/img.png"));
  • 谢谢,这可行

标签: c# wpf


【解决方案1】:

将图像的Build Action 设置为Content,将Copy to Output Directory 属性设置为Copy if newer

这应确保在构建时将其复制到.exe(通常为bin/Debugbin/Release)的输出目录。 该路径是相对于.exe 而不是项目。

另一个选项是将Build Action 设置为默认值Resource,并使用pack URI 指定路径。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-26
    相关资源
    最近更新 更多