Saturday, April 21, 2012

Silverlight : Change Images In Specific Time Interval in Different Thread

In Silverlight or Windows Phone 7, sometimes you may have requirement to change ImageSource in time interval.

User have need to Rotating Images one by one every 1 minutes.

To Rotate Image, we need to create Timer and we have to set Image source in another thread that not afftect the current thread.

Below is code snippet.

   private Timer timer;
   private object locker = new object();
   private int count = 0;

   private void StartTimer()
   {
       timer = new Timer(ChangeImage, null, 0, 1000);
   }
   private void ChangeImage(object state)
   {
      try
      {
          lock (locker)
          {
              string imgString = string.Empty;
              switch (count)
              {
                   case 1:
                      imgString = "/MyApplication;component/Images/First.png";
                      break;
                   case 2:
                      imgString = "/MyApplication;component/Images/Second.png";
                      break;
                   case 3:
                      imgString = "/MyApplication;component/Images/Third.png";
                      break;
              }
              Deployment.Current.Dispatcher.BeginInvoke(new Action(() =>
              {
                   Uri uri = new Uri(imgString, UriKind.Relative);
                   ImageSource imgSource = new BitmapImage(uri);
                   NearImage.Source = imgSource;
                   count = count + 1;
                   if (count == 4) count = 1;
              }));
          }
      }
      catch (Exception)
      {

      }
   }

In abovo source, i am changing image source every 1 minutes and converting String to ImageSource.

No comments:

Post a Comment