VS2019 - VSIX - 无法在运行时找到资源 (.png)

问题描述 投票:0回答:1
c# wpf resources visual-studio-2019
1个回答
0
投票

您可以尝试以下代码。

如果“属性”窗口中的“构建操作”为“资源”:

<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 替换为图像控件的名称。这些代码隐藏方法根据构建操作配置动态加载图像。

© www.soinside.com 2019 - 2024. All rights reserved.