About Me

My photo
Northglenn, Colorado, United States
I'm primarily a BI Developer on the Microsoft stack. I do sometimes touch upon other Microsoft stacks ( web development, application development, and sql server development).

Monday, February 18, 2008

Lights Out Game (XAML)

I figured I should start learning Xaml, since it is used in WPF and Silverlight. I found this nice tutorial on Code Project: http://www.codeproject.com/KB/silverlight/SilverlightsOut.aspx on how to make a game as a introduction to silverlight.

I however first decided to make it a WPF application to try my hand at that first. One of the first things I learned was about the error:

The calling thread cannot access this object because a different thread owns it.

In the original he had it setup to use the HTMLtimer use the Tick event to move the background of stars like so:

System.Windows.Browser.HtmlTimer timer =

   new System.Windows.Browser.HtmlTimer();

timer.Interval = 1;

timer.Enabled = true;

timer.Tick += new EventHandler(timer_Tick);


I figured that I would need to change this to use the Timer class:

Timer timer_error = new Timer();

timer_error.Interval = 1.0;

timer_error.Enabled = true;


timer_error.Elapsed += new ElapsedEventHandler(timer_error_Elapsed);

Then I got the error, which I then found:

"The .NET Framework 2.0 supports several timer objects, among them System.Timers.Timer, System.Threading.Timer, and System.Windows.Forms.Timer. However, these timers cannot be used directly by a WPF application since they run in a different thread than the one running the WPF UI."

(source: http://blogs.msdn.com/wpfsdk/archive/2006/06/23/Animating-Traffic-Map-Image-Data.aspx)

The solution is to use the System.Windows.Threading.DispatcherTimer like so:

System.Windows.Threading.DispatcherTimer timer  = new DispatcherTimer();  

timer.Interval = new TimeSpan(0,0,0,0,85);


timer.Tick += new EventHandler(timer_Tick);


I also had to change little things through out the program to get it to work, such as:

void timer_Tick(object sender, EventArgs e)


   double currentLeft = (double)background.GetValue(Canvas.LeftProperty);

   // get current left position of background

   if (currentLeft <= 0)


      // move background pixels over

      background.SetValue(Canvas.LeftProperty, currentLeft + 2);




     // reset backgrounds position

     background.SetValue(Canvas.LeftProperty, currentLeft - 340); 

     //instead of

    background.SetValue(Canvas.LeftProperty, -340);




I still have lots to learn. Currently I'm still adding more functionality to the app. I'm thinking that I should add a "restart" and make a auto-solve.

Technorati Tags: ,,,

No comments: