简体   繁体   中英

Setting WPF Window Background Image at App Start Up

I have an application that shows a different background images according to environment state, this app is launched at user logon via Windows Registry (HKEY_CURRENT_USER).
After user login the application is launched but it crashes afterward, complaining that the Uri for the image is not valid.
Notably if the application is launched manually by the user (ie double clicking) all works fine, and the corresponding image is successfully loaded.
Images are configured with Build Action = None, and Copy to output directory= Copy if newer .

This markup in my main window:

<Window.Background>
    <ImageBrush x:Name="imgBackground" ></ImageBrush>
</Window.Background>

Then in codebehind I want to set the corresponding image:

imgBackground.ImageSource = 
     new BitmapImage(new Uri(@"Resources\Background.png",UriKind.RelativeOrAbsolute));

Images are configured with Build Action = None, and Copy to output directory= Copy if newer .

Better load the image as embedded resource.

Set the Build Action to Resource (and do not copy to output directory), and load it via a Resource Pack URI :

imgBackground.ImageSource = new BitmapImage(
    new Uri("pack://application:,,,/Resources/Background.png"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM