Home » Microsoft Technologies

Changing Background-Image randomly

Hi there

I want to change the Apps-Background randomly on every page in my App.

I thought it would be cool to implement this in the App.xaml. But how can I do this?

    <ImageBrush x:Key="PhoneBackgroundBrush" ImageSource="THIS_SHOULD_BE_DYNAMIC" />

Perhaps I can write a function for every page which changes the ImageSource randomly ... but I think I could implement this easier.

Any ideas?


Thank you...Greetings casaout



8 Answers Found


Answer 1

I could not get the background brush to update without adding code to each page  but I could get close to what you describe by using an Image control. 

1. I created a class to hold a List of BitmapImages and a property "Image" that returns a random BitmapImage from the list:

  public class RandomImage 
    private List<BitmapImage> m_images;
    private Random m_rnd;
    private static int NumImages = 8;

    public RandomImage()
      // load images here...      
      m_rnd = new Random(DateTime.UtcNow.Millisecond);
      m_images = new List<BitmapImage>(NumImages);

      for (int i = 0; i < NumImages; i++)
        BitmapImage bi = new BitmapImage();
        bi.CreateOptions = BitmapCreateOptions.None;

        bi.UriSource = new Uri("Images/" + (i + 1).ToString() + ".jpg", UriKind.Relative);

    public BitmapImage Image
        int item = m_rnd.Next(0, NumImages - 1);

        return m_images[item];

 (Note: My class initializer assumes I have included 8 images with names 1.jpg through 8.jpg, this was just a convenient way for me to test.  My class does not implement  any error checking, you will want to add error checking in your own code.)

2. I made a static reference to this class in App.XAML:

    <cls:RandomImage x:Key="MyImages" />        

3. I added an Image control to each page with DataContext set to the static class instance and which binds to the "Image" property:

  <Image x:Name="bkgndImage" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Stretch="Fill"
      CacheMode="BitmapCache" Grid.RowSpan="3" Source="{Binding Image}" MinHeight="110" MinWidth="100" 
      DataContext="{StaticResource MyImages}" />

note: there may be better ways to do this... if anyone sees a problem with my solution please speak up. :)

I hope this helps.


Answer 2

hi Eric

Thank you for your answer and sorry for my late reply. The idea of using a class to handle the random-pic is great!

Unfortunately I can't manage to try your code, because I have a problem in the App.xaml when I write  in <cls:RandomImagex:Key="MyImages"/>  between <Application.Resources> and </Application.Resources>. The failure-Message is:

The type 'cls:RandomImage' was not found. Verify that you are not missing an assembly reference and that all reference assemblies have been built.

I tried to include the RandomImage-Class to App.xaml, but unfortunately nothing works. What exactly means "cls:" and do you have an idea how to correct the error?

Thank you very much!

Greeting, casaout


Answer 3

Sorry about that, I was trying to keep the post consise and so didn't include the namespace definition.  You need to add a statement like the following one to the <Application ...> block at the top of App.XAML:


where "XXX" is the namespace in which you defined the RandomImage class.  Note: the namespace alias "cls" is of my own choosing, you can use a different alias if you want as long as it does not conflict with any other namespace alias in the same scope.


Answer 4

hi Eric

Sorry for asking you again, but unfortunately I'm not able to add the statement in the <Application ... > - Tag. I really see, that I'm a newbie ...

I tried this in the App.xaml:


The RandomImage.cs - File is saved on the same level (in the project) as the App.xaml. My current APP-Name is PackApp. So I thought  I should write  PackApp.RandomImage.

The error-message is: "Undefined CLR namespace. The 'clr-namespcae' URI refers to a namespace 'PackApp.RandomImage' that is not included in the assembly.

Unfortunately I couldn't figure out what is meant with the assembly...

In the <Application.Resources>-Tag I wrote: <cls:RandomImage x:Key="MyImages" />

What am I doing wrong?

Thousand thanks!

Greetigns casaout


Answer 5

the "clr-namespace" should refer to the "namespace" name used in the class definition.

For example, in my test projects "RandomImage.cs" file the namespace was "WPL_LKG5"

namespace WPL_LKG5
  publicclass RandomImage 

so in my App.xaml the clr-namespace declaration looks like this:


I hope this helps.


Answer 6

Hi Eric,

Thank you for your help. Now it works fine for me. Usually everything works perfectly.

Unfortunately, sometimes there appears no image. I could not figure out the error with debugging,... I solved it by choosing a default-image which appears when the RandomImage-Error occurs. I know this is not perfect, and so I would appreciate every tip to solve my problem.

Thanks, casaout


Answer 7

It could be that one or more image fails to load.  The sample code assumes the image loads immediately and without error.  Instead of adding the BitmapImage object to the list right away you could wait for the ImageOpened event.

  In this case you would also want to use "m_images.Count", instead of "NumImages", when generating the random index.



Answer 8

hi Eric

Luckily, I could solve my problem. There was a problem with the random-number. With the code (in the RandomImage.cs class)

                int item = m_rnd.Next(1, NumImages);
                return m_images[item - 1];

it works perfectly :-)


Thank you very much!

Greetings casaout!



Hi All,

Does anyone know how can you change the backround colour and image of a tab control Heading. I can change the colour and image of the Tab page but cannot figure out how can I change the heading tabs i.e Tab Page 1 and Tab page 2 etc.

Changing the image and colour on the Tab Page property changes it of the entire tab page but the Heading Tabs remain unchanged.




Does anyone know if it is possible to set the main screen's background image? If so how?

when we enter parameter, i have found background image like Microsoft Sql server reporting services).

how i can change this image? 


The button already uses a resource image as a background and everything works but I the function to change the button background image again.



I use this function to change a button Background Image:


private: System::Void CaratHack(System::Object^ sender, System::EventArgs^ e) {
        this->button4->BackgroundImage = (cli::safe_cast<System::Drawing::Image^ >(resources->GetObject(L"button8.BackgroundImage")));




But I'm getting these a errors:

error C2065: 'resources' : undeclared identifier

error C2227: left of '->GetObject' must point to class/struct/union/generic type



I think I need to declare "resources"? If yes, then how?




Thank you all very much, it will really help me!



How do we change the background image of a button at runtime? I just wanted to know the code of open dialogue box which I would use to select the image from a pc.






I would like to change the background-color in my XSLTListView, when the ms-newgif is visible in a row.

How can I check in XSLT if the image is vivisble ?




I have created an asp.net website using visual studio express 2008.  I am having trouble mapping a path to my image folder from other files in the website.

My image folder's path is http://localhost/Cafeteria/Image/MyImage.gif

My aspx page that I want to map from is http://localhost/Cafeteria/Submeals/burgers.aspx

In my /burgers.aspx I have the following code:



<divid="bk"runat="server"style="border-style: double; border-width: thin; width: 680px; height: 680px; ">




 My http://localhost/Cafeteria/Submeals/burgers.aspx.vb page has the following code.


Sub Page_Load(ByVal sender AsObject, ByVal e As System.EventArgs) HandlesMe.Load

     bk.Style.Add("BACKGROUND-IMAGE", "url("~/image/food/MyImage.gif)")

end sub


However, my background image doesn't load.  Any help would be appreciated.

Thanks, Photon







I am trying to add my graphics folder to the resources folder in my project but I get some kind of error...

That's the easy question.

Now, I have a panel container in which I want to show an image that will be change about 5 times when I click on my background change button...

What codes do I need to use for this?

Any information would help.


Thanks a lot!





I have an windows application in c# and its uses step by step .. like a wizard. after completing each step i need to change the background image of form. so when I do this. the forms  flickers...

And I have also tried.  "doublebuffered = true" but this also not working..!

Please help me with this.



I know how to set the <param name="background" value="transparent"> and the <param name="windowless" value = "true" in order to make the background transparent, so it will show the background of the div that I placed my SL app into. 

I have figured out how to use a viewbox, and percentages in the object tag to get the application to resize when the browser is resized.   

The issue is that the background HEIGHT seems to be fixed - as when I resize my browser (usually smaller) - the application inside the <object> resizes, as does the <div> but the BACKGROUND HEIGHT DOES NOT CHANGE. 

I found this explanation:

 "So long as Windowless is false, in many cases the Background color of a Silverlight plug-in will never be visible. The content you specify as RootVisual totally covers the background, if you use the recommended technique of leaving Height and Width of any root visual unset so that it uses the automatic behavior of filling all available space in the plug-in content area."

http://msdn.microsoft.com/en-us/library/cc838148(v=VS.95).aspx but do not know how to implement it.  I want the plug in content area (background) to resize also...

I can supply the code if you need it (c#, XAML, and HTML)  I created the app in Expression Blend.  

Thanks in advance


Hello Friends !

I want to fix image heigt and to get proportionately it's width ....

First of all how to get Uploaded image height and width then crop the image

with one fixed height and it's width

 Main thing I need Height FIX and Width should be flexible

Please help


sankarshan parida

Hello to everybody,Smile

I'm a beginner in aspnet programming and I thought to become a member of this forum to learn better how to

program in this language (I use c# as code-behind language and visual studio 2008 environment).

I have a problem to solve: I want to display, on an aspnet page load, 12 random images taken from a mysql


I used connector-net in order to make mysql recognized by visual studio, I established a connection with the

database and I could display the content of 12 random rows of the table (eg ImageName, see below).

The database contains these columns:

ImageCode, ImageName, MaskName, ImageType

For example for the first row I have:

1 (ImageCode)

'C:\Inetpub\wwwroot\kf2\images\fuoco_bmp\fire10_res_res.bmp' (ImageName)


0 (ImageType)

I post you the code of the pageload I have written:

protected void Page_Load(object sender, EventArgs e)

MySql.Data.MySqlClient.MySqlConnection conn;

string myConnectionString =

conn = new MySql.Data.MySqlClient.MySqlConnection(myConnectionString);

string sql = "SELECT * FROM images ORDER BY RAND() limit 12";

MySqlCommand cmd = new MySqlCommand(sql, conn);
MySqlDataReader rdr = cmd.ExecuteReader();

while (rdr.Read())
Response.Write(rdr[0] + " -- " + rdr[1]);


With this code I display the url of 12 random images but I want to display the images itself.

Can anyone tell me how can I do step by step with the relative code?

Thanks in advance, I can't proceed


Hi there,

I have a GridView with an alternating Css style. The GridView has a column called tradeId. What I want to show is an alternating colour based on a change in the tradeId. Is this possible? It will make it easier on the eye to group trades together by colour. Here's the GridView code as it is right now:

            PageSize="30" >
                <asp:BoundField DataField="tradeId" HeaderText="Trade ID" />
                <asp:BoundField DataField="orderId" HeaderText="Order ID" />
                <asp:BoundField DataField="signalTypeId" HeaderText="Entry" />
                <asp:BoundField DataField="orderDateTime" HeaderText="Order Date/Time" DataFormatString="{0:d MMM yyyy HH:mm}" />
                <asp:BoundField DataField="profit" HeaderText="Pips profit" DataFormatString="{0:F1}"  />



Hallo there,

First of all I don't know if I am posting in the right forum, so let me know if there is another forum for this issue.

My form text and entire page formating changes once a while and I don't know why. e.g. font color, background color of certain paragraphs or table look changes, it seems randomly, I think it has something to do with the style but I don't know how to avoid this repeated text formating loses.

In details:

U am using Visual Studio 2010 Professional and is set for Visual Web Development.

I create a new form e.g. default.aspx link it to a master page and the master page is linked to a css file (style sheet file) that contains only general and basic formatings and I hardly change any thing in this css file.

I format my default.aspx. and later the formating chanegs by it self and I have to change it back manualy. Most of the time I have to create a new form. link it to the master page and copy the text, tables and so on from the original page to the new page and then delete the original page. but even the new page chnages later. and so on. I don't know how to avoid that!

Any idea's?

Thanks in advance




I have a strange one here that I can't seem to find much in the way of solutions. Even a glimpse of where to start looking would be great.

We have several content types setup at the site level, with columns (fields). About half a dozen times now, a column will flip to read only at the LIBRARY level only. So, when we go to edit the file properties, the fields in question don't show up in the form. If we open the site in Designer, go to the library, then content types, and then columns, and click on "Show read only", it appears. However, we can't find out how to change it back to editable.

So my question: 1. Any clue why this would be randomly happening at the library level? We cannot duplicate the error intentionally and 2. How might we go about fixing the column back to "edit"?

I will tell you we've fixed some by going into library settings, setting the column to "hidden", SAVE, set it back to "Optional", and it magically becomes editable again. However, this doesn't always work, and we've had to revert to recreating the column, which is increasingly becoming a non-option as our content grows.

Thanks, guys!


Hoep this si simple I would like to change the image in an image button when the user hovers over it ..can anyone help






Just wondering if anyone has ever managed to find a way to have a
datagridview image button column in a template field which  display different images on different rows depending
on some data element in the row. Our application needs to display a series
of fees charged against an account column which will be either less then 500, 500 to 1000 or >1000. Some of those fees are charged at a full rate, others at a partial rate, and some are not charged at all. The user
would like to see a simple 3-state graphic which would convey the simple
info: full-charge, partial-charge, or no-charge. Sounds easy enough but
I've not yet managed to find a way to do this. Every time I attempt to
modify the individual cell's graphic it seems to want to change the graphic
for all the rows.

Any way around this issue?


Ok i have a picturebox and i have a image with a blue and red square. When i click a button it pust that image into the picturebox as background image. The background image proerty is set to tile. but when i click on my form to draw the image to it, it just draws the original not the one that has the tile effect from the picturebox. Is there a way i can do this to keep the tile effect? - Thanks civilwarrock

i want to be able to enable or set a button for double click to launch a program but dont know how to do the double click method can anyone please help me i am using c# laungage 




I am trying to create a custom drop shadow effect on a form without any borders. I have a PNG image (supporting transparency) that has the shadow required on but I'm not able to apply it to the background image property of the form and achieve the transparency I need.

How can I achieve this custom drop shadow with images or in code? (Not the default shadow, I need the shadow to be fully customizable)


Thanks for any help in advance,



<< Previous      Next >>

Microsoft   |   Windows   |   Visual Studio   |   Sharepoint   |   Azure