2017-01-01 24 views
0

我在網格中有一個按鈕,我希望它在5秒後被禁用。我試圖通過計時器的Elapsed事件和啓用屬性來完成此操作。這裏是我的按鈕 -更新按鈕的定時器已消逝事件的狀態

<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秒後啓用。

+1

刷新狀態:http://stackoverflow.com/a/783121/4832634 –

回答

1

您需要提高命令的CanExecuteChanged事件。我不知道你的「命令」類中實現,但它應該有一個公共的方法提出這個事件:

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())); 
}