S.John Hawkins

Hi friend's,

How to bring the timer control in XAML.

I have a status bar in which i want to display the current time with seconds.

I am using this code..

sbar- is the status bar name..

TextBlock txtblk = new TextBlock();

txtblk.Text =Convert.ToDateTime(DateTime.Now).ToLongDateString();

sbar.Items.Add(txtblk);

I want to display the Time with running seconds in the status bar..

Waiting for the reply..

Thanks,

S.John Hawkins.



Re: Windows Presentation Foundation (WPF) How to bring the timer control in XAML..

Prasad Honrao

You can use System.Timers.Timer class & handle the Elapsed event.

Display the time using Elapsed event handler.





Re: Windows Presentation Foundation (WPF) How to bring the timer control in XAML..

Deepak Kapoor

Hi S.John,

Have a Timer member in your class:

System.Timers.Timer timer = new System.Timers.Timer();
You can then do the following in your constructor or maybe Window.Loaded event handler:

timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);

timer.Interval = 1000;
timer.Enabled = true;
Finally in the ElapsedEventHandler you could put the following code:
myTextBox.Text = DateTime.Now.TimeOfDay.ToString();

When you run your code, you will get an error The calling thread cannot access this object because a different thread owns it.

To get around this issue you can use the following code in your ElapsedEventHandler:

this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, 
new
System.Windows.Forms.MethodInvoker(delegate()
{
myTextBox.Text = DateTime.Now.ToLongTimeString();
}
));
You will notice a dependency on System.Windows.Forms. If you don't want this then you can do as suggested here.






Re: Windows Presentation Foundation (WPF) How to bring the timer control in XAML..

S.John Hawkins

Hi,

I used the following code and now its's working fine.. Thanks for ur reply...

TextBlock txtblk = new TextBlock();

System.Windows.Forms.Timer time = new System.Windows.Forms.Timer();

time.Start();

time.Tick += new EventHandler(time_Tick);

statusbar.Items.Add(txtblk);

void time_Tick(object sender, EventArgs e)

{

txtblk.Text = DateTime.Now.ToString();

}

Thanks,

S.John Hawkins.