引用Visual Studio中WPF项目中的图像文件

本文关键字:图像 文件 项目 WPF Visual Studio 引用 | 更新日期: 2023-09-27 18:37:26

我想将图像加载到带有短路径名的 WPF 项目中。详情如下。

我有一个如下所示的 WPF 解决方案:

Solution 'GB" (16 projects)   
   ABApp
     Properties
     References
     ...   ...   
   ImageApp
     Properties
     References
     images
        mona.jpg
     App.xaml
        App.xaml.cs
     Window1.xaml
        Window1.xaml.cs

我想看看ImageApp项目。

App.xaml文件如下所示:

<Application x:Class="GB.App"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         StartupUri="Window1.xaml">
    <Application.Resources>
    </Application.Resources>
</Application>

App.xaml.cs只是定义了从Application派生的类App

Window1.xaml文件构造一个 UI,然后Window1.xaml.cs生成一个绘图区域,其中将显示各种图像内容。

在该 C# 文件中,为了加载我要显示的图像images/mona.jpg,我最终编写了如下内容:

        Image myImage;
        BitmapImage myBitmapImage = new BitmapImage();
        myBitmapImage.BeginInit();
        myBitmapImage.UriSource = 
             new Uri("../../images/mona.jpg", UriKind.RelativeOrAbsolute);
        myBitmapImage.EndInit();
        //set image source
        FormatConvertedBitmap newFormatedBitmapSource = new FormatConvertedBitmap();
        newFormatedBitmapSource.BeginInit();
        newFormatedBitmapSource.Source = myBitmapImage;
        newFormatedBitmapSource.DestinationFormat = PixelFormats.Bgra32;
        newFormatedBitmapSource.EndInit();
        bmpSource = newFormatedBitmapSource;
        myImage.Source = bmpSource;
        BuildRenderTransform();

(我为这段代码道歉 - 这是对真实情况的一种简化,所以它可能不是完美的字母。

我的问题是关于 Uri 的:我必须在 Uri 的前面写../../,以便执行程序(最终以 ImageApp/bin/Debug 结尾)知道它必须上升两级,然后向下进入images文件夹。有没有办法让我写出像new Uri("images/mona.jpg", ...)这样的东西?我是否可以告诉 WPF 源目录应用作相对搜索的起始路径?

我承认,整个Uri的事情对我来说主要是令人困惑的,尽管我已经阅读了Microsoft的帮助文章和几个StackExchange问题/答案。

我怀疑(和模糊的记忆)通过向项目的 xaml 添加一些东西,我可以实现这一目标,但我似乎做不到。

有什么想法吗?

引用Visual Studio中WPF项目中的图像文件

我不确定(现在无法检查),但请尝试指定这样的东西

new Uri("/ImageApp;component/images/mona.jpg");

并确保您在参考文献中有图像应用程序