xaml图像在运行时不显示,但在设计时显示(VB,wpf)-为什么



我正在努力理解WPF,并创建了一个WPF测试项目。我在每个文件夹中都放了一个monkey01.jpg图像,从项目的根开始,在层次结构中向上移动,到debug文件夹。在MainWindow上,我创建了一个Image,并定义了源属性以指向monkey01.jpg,它在设计视图中正确显示。但当我运行它时,图像不会出现。

  • 如果我将图像文件作为资源添加到项目,它将在运行时显示,这是预期的。(但这不是我在这里测试的内容)
  • 如果在xaml文件中,我写入绝对路径,如Source="C:UsersUserDesktopvisual_studio_projectsWpfApplication1monkey01.jpg中所示,它也将显示
  • 但是,如果我使用相对路径(如下面的示例),则不会显示图像。就好像在执行时,程序不会在项目文件夹及其子文件夹中运行;相反,它运行在其他无法访问图像的位置。为什么会有这种行为?我错过了什么

这是MainWindow.xaml代码:

<Window x:Class="MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Image x:Name="Thumbnailtest" Source="monkey01.jpg" />
    </Grid>
</Window>

谢谢!

您需要在图像的属性窗口中将Copy to Output Directory设置为"如果更新则复制"。

当我将图像设置为Resource并且不复制时,这里的工作很好,请注意,我将猴子图像更改为.png,并为其创建了一个文件夹(数据/图像)。

<Window x:Class="MasoneryLibrary.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:MasoneryLibrary;assembly=MasoneryLibrary"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <Grid>
        <Image Source="Data/Images/monkey01.png" HorizontalAlignment="left" VerticalAlignment="Top" Width="290" Height="456"  Margin="285,0,-58,-136" Stretch="None" StretchDirection="DownOnly"/>
    </Grid>
</Grid>

嗯。。这是图书馆吗为了安全起见,您应该使用URI包

带有URI包:

<Image Source="pack://application:,,,/MasoneryLibrary;component/Data/Images/monkey01.png" HorizontalAlignment="left" VerticalAlignment="Top" Width="290" Height="456"  Margin="285,0,-58,-136" Stretch="None" StretchDirection="DownOnly"/>

希望它能有所帮助!

干杯,

Stian

最新更新