我在网格中有一个按钮,我希望它在5秒后被禁用。我试图通过Timer的Elapsed事件和Enabled属性来做到这一点。这是我的按钮 -
<Window.DataContext>
<local:VM/>
</Window.DataContext>
<Grid>
<Button Content="Button" Command="{Binding ACommand}"/>
</Grid>
我试过以下代码 -
public class VM
{
Timer timer;
public Command ACommand { get; set; }
public VM()
{
timer = new Timer(5000);
timer.Start();
timer.Elapsed += disableTimer;
ACommand = new Command(Do, CanDo);
}
bool CanDo(object obj) => timer.Enabled;
void Do(object obj) { }
void disableTimer(object sender, ElapsedEventArgs e)
{
timer.Stop();
timer.Enabled = false;
}
}
5秒后仍然启用。
答案 0 :(得分:1)
您需要引发命令的CanExecuteChanged事件。我不知道你的命令&#34; class已实现,但它应该有一个公共方法来引发此事件:
public class Command : System.Windows.Input.ICommand
{
private readonly Predicate<object> _canExecute;
private readonly Action<object> _execute;
public Command(Action<object> execute, Predicate<object> canExecute)
{
_execute = execute;
_canExecute = canExecute;
}
public bool CanExecute(object parameter)
{
if (_canExecute == null)
return true;
return _canExecute(parameter);
}
public void Execute(object parameter)
{
_execute(parameter);
}
public event EventHandler CanExecuteChanged;
public void RaiseCanExecuteChanged()
{
if (CanExecuteChanged != null)
CanExecuteChanged(this, EventArgs.Empty);
}
}
然后,只要您想刷新命令的状态,即每当您希望再次调用CanDo委托时,就需要调用此方法。确保在UI线程上引发事件:
void disableTimer(object sender, ElapsedEventArgs e)
{
timer.Stop();
timer.Enabled = false;
Application.Current.Dispatcher.Invoke(new Action(() => ACommand.RaiseCanExecuteChanged()));
}