Is there a way to execute a command when property changes with specified binding delay?
As an example let's use CheckBox that has property IsChecked with Delay=1000 (1 sec) and Command that invokes when IsChecked property changes:
MainWindow.xaml:
<CheckBox Command="{Binding Command}"
Content="Hello"
IsChecked="{Binding IsChecked, Delay=1000}" />
MainWindow.xaml.cs:
private bool _isChecked;
public bool IsChecked
{
get { return _isChecked; }
set
{
if (_isChecked != value)
{
_isChecked = value;
OnPropertyChanged();
MessageBox.Show("Property Changed");
}
}
}
public ICommand Command { get; } = new RelayCommand(obj => MessageBox.Show("Command Invoked"));
When clicking on checkbox the MessageBox.Show("Command Invoked") invokes first and then MessageBox.Show("Property Changed");
Final output:
"Command Invoked" -\> after 1 sec delay -\> "Property Changed"
You can execute the operation from the property
set(), depending on the delay of theBinding.Or you delay the operation explicitly using a timer or
Task.Delay:To replicate the delay behavior of the binding engine, you would have to use a timer and reset it on every invocation and honor the latest change/command parameter exclusively.
The following example uses the
System.Threading.Timer(if you need to access UI elements, orDispatcherObjectinstances in general, you should use theDispatcherTimerinstead):