I added a new class.cs to my project. Very simple for some.
I have textbox that I want to populate the date and time. The code is complete works fine. I want to stay organize, I don't really want to add anymore code to the MainWindow.cs. I'm having trouble fomatting the Timer.cs to bind with textbox on the MainWindow.
The XAML code is
<TextBox Height="41" Text="{Binding CurrentDateTime}"
|
The Timer.cs is the following:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace WpfApplication9 { public partial class Timer { private Timer clockTimer; public Timer(); {
clockTimer = new Timer(1000); clockTimer.Elapsed += new ElapsedEventHandler(clockTimer_Elapsed); clockTimer.Start(); DataContext = this; } void clockTimer_Elapsed(object sender, ElapsedEventArgs e) { Dispatcher.BeginInvoke(new Action(UpdateCurrentDateTime)); } public string CurrentDateTime { get { return (string)GetValue(CurrentDateTimeProperty); } set { SetValue(CurrentDateTimeProperty, value); } } public static readonly DependencyProperty CurrentDateTimeProperty = DependencyProperty.Register("CurrentDateTime", typeof(string), typeof(Mainwindow), new UIPropertyMetadata(string.Empty)); private void UpdateCurrentDateTime() { CurrentDateTime = DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss"); } }
|
This is my first time I'm trying to establish a class(.cs) in a project. any help would be great
Thanks
RIck MuellerPosted Mar 11, 2010, 3:57 PM
Thank you for your help, Still not able to get it wired up
Raaj KumarPosted Mar 3, 2010, 5:57 AM
Nothing big you have to do simply inherit INotifyPropertyChanged and implement the event. Like this,
public string CurrentDateTime
{
get { return (string)GetValue(CurrentDateTimeProperty); }
set
{
SetValue(CurrentDateTimeProperty, value);
PropertyChanged(this, new PropertyChangedEventArgs("CurrentDateTime"));
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged = (t, e) => { };
#endregion
Try this and let me know if you face any problem
Regards,
raaj
Sam HobbsPosted Mar 2, 2010, 1:00 PM
I think you should create either a UserControl or a Control that has a Timer and a TextBox in it. You can create the Timer in code if you want to or drag and drop from the toolbox. You will need to use Invoke or something similar to update the TextBox. UserControls and Controls are a very effective way to modularize your code.