简体   繁体   中英

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?

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM