ImageBrush throws exception when trying to set Win

2019-07-10 13:24发布

问题:

I'm trying to set the background of my WPF window to an image but I'm getting this exception when I try to run it:

A first chance exception of type 'System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll Additional information: 'Provide value on 'System.Windows.Baml2006.TypeConverterMarkupExtension' threw an exception.' Line number '8' and line position '10'.

I don't want to add the image to the project, as I would like to be able to change the image at runtime. My intention is to use databinding to set the background picture during start-up once I have this bit working.

Source Code:

<Window x:Class="ColinsTest.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Colin's Test Application" 
    WindowStyle="None"
    WindowState="Maximized">
<Window.Background>
    <ImageBrush 
        ImageSource="DeLaRue-Background.jpg"/>
</Window.Background>
<Grid></Grid>
</Window>

Any Ideas? Thanks

回答1:

Wrong. It should be set to CONTENT not Resource.

Include in your project (use the file explorer)

Right click on the image > Properties > Advanced.

Build Action: Content

Copy to Output Directory: Copy always.



回答2:

Your image's build action is probably set to Content, change it to Resource

Set the item (your image file) to be a Resource. (In Visual Studio) Right click,Properties,Build Action,Resource



回答3:

I had the same problem with

 <Button>
     <Button.Background>
         <ImageBrush ImageSource="/Resources/icon_done.png">
     </Button.Background>
 </Button>

I used / before Resources and it work correctly, but i used solution with properties image ->Properties->Build to Resources. These two actions solved my issue.



回答4:

Add the forward "/" to the location

Then the whole ImageSource string should look like

<ImageBrush ImageSource="/Resources/Image1.png" Stretch="None" />