在结算日期时间还剩4分钟时启用按钮
本文关键字:4分钟 启用 按钮 日期 时间 | 更新日期: 2023-09-27 18:27:30
我正在使用MvvmLight开发WPF应用程序。我想在结算时间还剩4分钟时启用按钮。它应该在UI中自动启用。我应该使用线程来持续跟踪CurrentUTCtime和mytime的差异吗?如果是,那么如何将线程与此代码一起使用?这是我的密码。
Datetime mytime = new DateTime(DateTime.Now.Year,DateTime.Now.Month,DateTime.Now.Day,22,0,0)
public RelayCommand Open
{
get
{
return Open?? (_open= new RelayCommand(ExecuteOpen, CanExecuteOpen));
}
private void ExecuteOpen()
{
_navigation.NavigationToSetBetsDialogue();
}
private bool CanExecuteOpen()
{
double? remainingMinutes = null;
DateTime CurrentUTCtime = DateTime.UtcNow;
remainingMinutes = mytime .Subtract(CurrentUTCtime).TotalMinutes;
if (remainingMinutes <= 4)
{
return true;
}
else
{
return false;
}
}
}
尝试使用DispatcherTimer:
private DispatcherTimer _Timer = new DispatcherTimer();
private bool _CanExecute;
private void StartTimer()
{
var mytime = new DateTime( DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 22, 0, 0 );
var interval = DateTime.UtcNow - mytime - TimeSpan.FromMinutes( 4 );
_Timer.Interval = interval;
_Timer.Tick += Timer_Tick;
}
private void Timer_Tick( object sender, EventArgs e )
{
_Timer.Tick -= Timer_Tick;
_CanExecute = true;
CommandManager.InvalidateRequerySuggested();
}
public ICommand Open
{
get { return new RelayCommand( ExecuteOpen, () => _CanExecute ); }
}
您可以使用can execute并检查运行时间,不需要单独的线程,因为can execute无论如何都会并行运行。。。
private DateTime _startTime;
private void StartCommandHandler(object obj)
{
_startTime = DateTime.Now;
}
private bool CanEnableButton(object arg)
{
return _startTime != DateTime.MinValue && DateTime.Now.Subtract(_startTime).Minutes >= 4;
}
希望它能帮助
您可以使用BackgroundWorker
执行此操作。首先你需要启动工人:
BackgroundWorker bgWrkr = new BackgroundWorker();
bgWrkr.DoWork += new DoWorkEventHandler(bgWrkrDoWork);
bgWrkr.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgWrkrRunWorkerCompleted);
然后实现事件的处理程序。DoWork
:
void bgWrkrDoWork(object sender, DoWorkEventArgs e)
{
while (mytime.Subtract(DateTime.UtcNow).TotalMinutes >= 4){ }
}
和RunWorkerCompleted
:
void bgWrkrRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
button.IsEnabled = true;
}
当然你必须启动工人:
bgWrkr.RunWorkerAsync();
您可以在初始化.bgWrkr.RunWorkerSync()后立即启动它;