views:

59

answers:

2

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

+1  A: 

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")));
Carko
Used the second, since I was defining a static constant. Thanks!
brunodecarvalho
+1  A: 

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

Guru Charan