设置窗口背景作为图像从运行时的驱动器

时间:2013-12-22 15:24:33

标签: c# wpf xaml

图片显示在设计器中,但在vs2013中作为调试运行时,它会出错: 如果exe直接与同一文件夹中的图像一起运行。

information: 'Provide value on 'System.Windows.Baml2006.TypeConverterMarkupExtension' threw an exception.' Line number '12' and line position '10'.

错误是bcoz它找不到图像。也是在xaml视图中,当悬停图像时,它说:

project file expected in c:\user\bsienn\docs\vs2013\project\wpf1\wpf1\image1.jpg

虽然照片确实在那条路上并且可用。

我想添加一个图像作为表单的背景,我不想在资源中添加图像,bcoz我希望在需要时更改图像。我已将图像放在exe文件中,也尝试将其放在bin / debug和主应用程序文件夹中(wpf1 / image1.jpg andsoso wpf1 / wpf1 / image1.jpg)。

这是xaml代码,请指导

<Window.Background>
    <ImageBrush ImageSource="image1.jpg"/>
</Window.Background>

App structure:
app.exe
image1.jpg
Desired outcome, form with background image

2 个答案:

答案 0 :(得分:1)

这将按照需要进行

XAML:

<Window.Background>
    <ImageBrush x:Name="MainFormBgrImg"/>
</Window.Background>
代码背后的代码:

BitmapImage bitimg = new BitmapImage();
bitimg.BeginInit();
bitimg.UriSource = new Uri(@""+AppDomain.CurrentDomain.BaseDirectory+"backgroundImg.jpg", UriKind.RelativeOrAbsolute);
bitimg.EndInit();
MainFormBgrImg.ImageSource = bitimg;

AppDomain.CurrentDomain.BaseDirectory: 返回app运行的当前工作目录,即c:\ users \ admin \ Desktop \

答案 1 :(得分:0)

将图像放在输出文件夹中不会使其可用于XAML。

您需要add image in your project并将Build Action设置为Resource

右键点击项目中添加的图片 - &gt;打开属性 - &gt;将构建操作设置为资源。