Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change WPF window background image in C# code

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)?

like image 549
biasedbit Avatar asked Oct 24 '10 18:10

biasedbit


People also ask

How do I change the background color in WPF?

Navigate to the Properties window, and click the Background drop-down arrow, and choose Red or another color in the color picker.

How do I add a background image in XAML?

In this article, you will learn how to develop background image in Univesal Windows Platform Application, using XAML and C sharp program. Requirements - Visual Studio 2015 Update 3. Step 1 - Open Visual Studio 2015 Update 3 and open the new project. The shortcut key, which can be used is Ctrl+Shift+N.


3 Answers

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"))); 
like image 104
Darko Kenda Avatar answered Sep 21 '22 12:09

Darko Kenda


Here the XAML Version

<Window.Background>     <ImageBrush>         <ImageBrush.ImageSource>             <BitmapImage UriSource="//your source .."/>         </ImageBrush.ImageSource>     </ImageBrush> </Window.Background> 
like image 27
WiiMaxx Avatar answered Sep 24 '22 12:09

WiiMaxx


The problem is the way you are using it in code. Just try the below code

public partial class MainView : Window
{
    public MainView()
    {
        InitializeComponent();

        ImageBrush myBrush = new ImageBrush();
        myBrush.ImageSource =
            new BitmapImage(new Uri("pack://application:,,,/icon.jpg", UriKind.Absolute));
        this.Background = myBrush;
    }
}

You can find more details regarding this in
http://msdn.microsoft.com/en-us/library/aa970069.aspx

like image 38
Gurucharan Balakuntla Maheshku Avatar answered Sep 23 '22 12:09

Gurucharan Balakuntla Maheshku