languages | products | page_type | name | ||
---|---|---|---|---|---|
|
|
sample |
Disable Command Source via System Timer Sample |
This sample shows how to enable and disable a command source via a Windows.System.Timers.Timer.
A Windows.System.Timers.Timer runs on a separate thread than the UI thread, so some extra work is needed to update the UI. Another way to solve this problem, and in most cases a better and more elegant way, is a use the DispatcherTimer. This is easier because the DispatcherTimer runs on the same thread as the UI Thread. For information, see the Disable Command Source via Dispatcher Timer Sample sample. There are times though when you may need to use a class that doesn't run on the UI thread, so this sample shows how to accomplish this.
Command sources, such as the MenuItem class and the Button class, listen to the CanExecuteChanged event on the RoutedCommand they are attached to in order to determine when they need to query the command to see if the command can execute on the current command target. Command sources will typically disable themselves if the command cannot execute and enable themselves if the command can execute, such as when a MenuItem gray's itself out when the command cannot execute.
The CommandManager notifies the RoutedCommand via the RequerySuggested event that conditions have changed with the command target. The RoutedCommand raises the CanExecuteChanged event which the command source listens to. Normally, this notification mechanism is adequate, but there are some situations where the CommandManager is unaware that the conditions have changed on the command target and thus the RequerySuggested event is never raised and the command source never queries the RoutedCommand. In these situations the CommandManager can be forced to raise the RequerySuggested event by calling InvalidateRequerySuggested.
The easiest way to use these samples without using Git is to download the zip file containing the current version (using the link below or by clicking the "Download ZIP" button on the repo page). You can then unzip the entire archive and use the samples in Visual Studio 2019.
- Select Build > Deploy Solution.
- To debug the sample and then run it, press F5 or select Debug > Start Debugging. To run the sample without debugging, press Ctrl+F5 or selectDebug > Start Without Debugging.