C# – Change WPF window background image in C# code

background-imagecwpf

I have a couple of Images configured as application resources.

When my application starts, the background of the main window is set via XAML:

<Window.Background>
    <ImageBrush ImageSource="/myapp;component/Images/icon.png" />
</Window.Background>

If a given event occurs, I'd like to change this background to another resource ("/myapp;component/Images/icon_gray.png").

I've tried using two constants:

private static readonly ImageBrush ENABLED_BACKGROUND =
    new ImageBrush(new BitmapImage(new Uri("/myapp;component/Images/icon.png")));
private static readonly ImageBrush DISABLED_BACKGROUND =
    new ImageBrush(new BitmapImage(new Uri("/myapp;component/Images/icon_gray.png")));

… but naturally, I get an exception with Invalid URI.

Is there a simple way to change the background image (via this.Background = ...) of a WPF window using either the pack Uri or the resource (i.e.: Myapp.Properties.Resources.icon)?

Best Answer

What about this:

new ImageBrush(new BitmapImage(new Uri(BaseUriHelper.GetBaseUri(this), "Images/icon.png")))

or alternatively, this:

this.Background = new ImageBrush(new BitmapImage(new Uri(@"pack://application:,,,/myapp;component/Images/icon.png")));