我在项目中添加了图像作为资源,如果我尝试将它添加到我的 WPF 项目中,它总是以
Error 1 The file images\background.png is not part of the project or its 'Build Action' property is not set to 'Resource'. C:\Users\Martinek\Documents\My\Learning.Dot.Net\WPF.8\WPF.8\Window1.xaml 21 47 WPF.8
我还尝试引用完整路径“file:///”等,即使将图像添加为资源也有相同的结果
另请参阅带有结果的 XAML 代码
<ImageBrush AlignmentX="Left" ImageSource="images/background.png" Stretch="Fill" />
请您参考如下方法:
我注意到您将 Copy to Output Directory 选项设置为“Do Not Copy”。
尝试将其更改为“始终复制”或“更新时复制”,看看是否有帮助。
更新
我刚刚编写了一个快速示例应用程序来尝试解决这个问题。它似乎工作正常,所以我会在此处发布我的代码,希望它能有所帮助。
<Grid>
<Grid.Background>
<ImageBrush x:Name="brush" AlignmentX="Left" ImageSource="images/have_the_dumb.jpg" Stretch="Fill" />
</Grid.Background>
</Grid>
在代码隐藏中,我添加了一些跟踪代码以查看 ImageBrush 认为它的 ImageSource 在哪里。
public ImageDisplay()
{
Trace.Listeners.Add(new TextWriterTraceListener(@"c:\happyface.trace.log"));
Trace.AutoFlush = true;
InitializeComponent();
Trace.WriteLine(String.Format("Image thinks it's in {0}", brush.ImageSource.ToString()));
}
在 Debug模式下运行时,您应该会看到一行写入输出窗口(以及 *.trace.log 文件),其中包含它认为图像所在的 URI。
我用我的解决方案根目录下的图像文件夹中的图像运行它。我尝试将图像设置为“内容”(“如果更新则复制”)以及“资源”(不复制),并且两次都成功运行。
希望这能为您指明正确的方向。
