2017-01-01 7 views
0

グリッド内にボタンがあり、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秒後に有効なまま。

+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())); 
} 
関連する問題