For the problem of DispatcherTimer in WPF you could refer to the following code. If your Machine class doesn't matter, you can put the properties and related methods directly in the ViewModel. Then bind the properties.
Xaml:
<StackPanel Orientation="Horizontal" Margin="250,0,0,0">
<Label Content="Date" Width="45" Height="30" />
<TextBox x:Name="txtboxdate" Width="150" Height="20" IsReadOnly="True" Text="{Binding Path=Mch.CurrentDate}"/>
<Label Content="Time" Width="45" Height="30" Margin="40,0,0,0" />
<TextBox x:Name="txtboxtime" Width="130" Height="20" IsReadOnly="True" Text="{Binding Path=Mch.CurrentTime}"/>
</StackPanel>
Codebehind:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new MachineViewModel();
}
}
public class MachineViewModel : INotifyPropertyChanged
{
public MachineViewModel()
{
_mch = new Machine();
}
private Machine _mch;
public Machine Mch
{
get
{
return _mch;
}
set
{
_mch = value;
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
public class Machine : INotifyPropertyChanged
{
private string _currentTime, _currentDate;
public Machine()
{
CurrentDateText();
DispatcherTimerSetup();
}
public string CurrentTime
{
get { return _currentTime; }
set
{
if (_currentTime != value)
_currentTime = value;
OnPropertyChanged("CurrentTime");
}
}
public string CurrentDate
{
get { return _currentDate; }
set
{
if (_currentDate != value)
_currentDate = value;
OnPropertyChanged("CurrentDate");
}
}
private void CurrentDateText()
{
CurrentDate = DateTime.Now.ToString("MM/dd/yyyy");
}
private void CurrentTimeText(object sender, EventArgs e)
{
CurrentTime = DateTime.Now.ToString("HH:mm:ss");
}
private DateTime _machineCurrentTime;
public DateTime MachineCurrentTime
{
get
{
return _machineCurrentTime;
}
set
{
_machineCurrentTime = value;
}
}
private void DispatcherTimerSetup()
{
DispatcherTimer dispatcherTimer = new DispatcherTimer();
dispatcherTimer.Interval = TimeSpan.FromSeconds(1);
dispatcherTimer.Tick += new EventHandler(CurrentTimeText);
dispatcherTimer.Start();
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.