您可以尝试以下代码。
如果“属性”窗口中的“构建操作”为“资源”:
<Image Source="pack://application:,,,/AssemblyName;component/Resources/progress_1.png" />
如果“构建操作”为“内容”并且“属性”窗口中的“包含在 VSIX 中”为 True:
<Image Source="pack://application:,/Resources/progress_1.png" />
以下是相应的代码隐藏方法,用于根据构建操作设置为资源还是内容来动态加载图像:
如果“属性”窗口中的“构建操作”为“资源”:
using System;
using System.Reflection;
using System.Windows;
using System.Windows.Media.Imaging;
namespace YourNamespace
{
public partial class YourWindow : Window
{
public YourWindow()
{
InitializeComponent();
string assemblyName = Assembly.GetExecutingAssembly().GetName().Name;
string imageUri = $"pack://application:,,,/{assemblyName};component/Resources/progress_1.png";
BitmapImage bitmapImage = new BitmapImage(new Uri(imageUri));
yourImageControl.Source = bitmapImage;
}
}
}
如果构建操作是内容并且包含在 VSIX 中为 True:
using System;
using System.Windows;
using System.Windows.Media.Imaging;
namespace YourNamespace
{
public partial class YourWindow : Window
{
public YourWindow()
{
InitializeComponent();
string imageUri = "pack://application:,,,/Resources/progress_1.png";
BitmapImage bitmapImage = new BitmapImage(new Uri(imageUri));
yourImageControl.Source = bitmapImage;
}
}
}
将 YourNamespace 替换为项目的实际命名空间,将 YourWindow 替换为窗口类的名称,将 yourImageControl 替换为图像控件的名称。这些代码隐藏方法根据构建操作配置动态加载图像。