Nal_Nalepka
Nal_Nalepka

Reputation: 11

Dynamically changing background color

In my Windows Phone 7 app, I want ContentPanel's background to change its color within a specified time (3 seconds in this case). Basically I want it to be "flashing".

But the problem is that the changes do not appear while the loop is working, the color changes only once, after the loop is done working. Why?

byte R;
TimeSpan ts = new System.TimeSpan(0, 0, 0, 3);
DateTime dt1 = new DateTime();           
DateTime dt2 = new DateTime();    

requirement = true;
while (requirement)
{ 
    R = Convert.ToByte(0.5 * 255 * (1 + Math.Sin(DateTime.Now.Millisecond)));
    ContentPanel.Background = new SolidColorBrush(Color.FromArgb(255, R, 125, 70));
    dt1 = DateTime.Now;
    dt2 = DateTime.Now;
    dt2.Subtract(dt1);
    if (dt2.Subtract(ts).CompareTo(dt1) > 0) requirement = false;
 }

Is it even possible?

Upvotes: 1

Views: 1768

Answers (3)

mdn
mdn

Reputation: 252

Try using the DispatcherTimer to do in async way.

The UI is not updated during your method execution, moreover if you work in the UI thread.

Upvotes: 0

rikkit
rikkit

Reputation: 1137

Looks like your loop is too tight.

Try this instead:

private DispatcherTimer _timer;

private void StartFlash()
{
  _timer = new DispatcherTimer();
  _timer.Interval = new TimeSpan(0,0,1);
  _timer.Tick += (s,e) => ChangeColour;
}

private void StopFlash()
{
  _timer = null;
}

private void ChangeColour() {
  // Your colour changing logic goes here
  ContentPanel.Background = new SolidColorBrush(Color.FromArgb(a,r,g,b));
}

Put that code in a class. Call StartFlash() somewhere. ChangeColour will execute every second.

Upvotes: 1

Machinarius
Machinarius

Reputation: 3731

You are asking for DateTime.Now way too fast so the difference will equate to 0 as DateTime's accuracy does not go as far as nanoseconds (Dates are marked by milliseconds from the unix epoch after all).

You might want to limit the while with more solid logic.

Upvotes: 0

Related Questions