当属性更改时,有没有一种方法执行命令,指定的绑定延迟?

作为一个例子,让我们使用CheckBox,它具有属性Iscury,延迟= 1000(1秒),以及当Iscury属性发生变化时调用的Command:

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"));

当点击复选框时,首先调用MessageBox.Show("命令已删除"),然后调用MessageBox.Show("属性已更改");

最终输出:

"Command Invoked" -\> after 1 sec delay -\> "Property Changed"

推荐答案

您可以从属性set()执行操作,具体取决于Binding的延迟.

或者使用计时器或Task.Delay显式延迟操作:

public ICommand SomeCommand { get; } = new RelayCommand(ExecuteSomeCommandDelayedAsync);

private async Task ExecuteSomeCommandDelayedAsync(object commandParameter)
{
  await Task.Delay(TimeSpan.FromSeconds(1));
  MessageBox.Show("Command Invoked");
}

要复制绑定引擎的延迟行为,您必须使用计时器,并在每次调用时重置它,并独占地遵守最新的更改/命令参数.

下面的示例使用System.Threading.Timer(如果您一般需要访问UI元素或DispatcherObject实例,则应改用DispatcherTimer):

public ICommand SomeCommand { get; } = new RelayCommand(ExecuteSomeCommand);

// Important: this Timer implements IDisposable/IDisposableAsync.
// It must be disposed if it is no longer needed!
private System.Threading.Timer CommandDelayTimer { get; } 
private object SomeCommandCommandParameter { get; set; }

public Constructor()
  => this.CommandDelayTimer = new Timer(OnCommandDelayElapsed);

private async Task ExecuteSomeCommand(object commandParameter)
{
  // Capture latest parameter value and drop the previous
  this.SomeCommandCommandParameter = commandParameter;

  // Start/reset the timer.
  // This timer is configured to execute only once (period time = 0).
  _ = this.CommandDelayTimer.Change(TimeSpan.FromSeconds(1), TimeSpan.Zero);
}

private void OnCommandDelayElapsed(object? state)
{
  SomeCommandOperation(state);
}

// The operation that the command is supposed to invoke after a delay
private void SomeCommandOperation(object commandParameter)
{  
  MessageBox.Show("Command Invoked");
}

Csharp相关问答推荐

需要深入了解NpgSQL DateTimeOffset处理

在依赖性注入和继承之间进行 Select

Microsoft. VisualBasic. FileIO. FileSystem. MoveFile()对话框有错误?

在一个模拟上设置一个方法,该模拟具有一个参数,该参数是一个numc函数表达式

.NET HttpClient、JsonSerializer或误用的Stream中的内存泄漏?

S能够用DATETIME来计算,这有什么错呢?

只有第一个LINQ.Count()语句有效

静态对象构造顺序

从依赖项容器在.NET 8中的Program.cs文件中添加IOC

在允许溢出的情况下将小数转换为长

HttpClient 415不支持的媒体类型错误

正在寻找新的.NET8 Blazor Web应用程序.如何将.js添加到.razor页面?

如何防止Visual Studio断点以红色突出显示到整行?

记录类型';==运算符是否与实现IEquatable<;T&>;的类中的';equals&>方法执行等价比较?

当`JToken?`为空时?

映射器-如何映射到多个实体

根据优先级整理合同列表

Xamarin.Forms项目中缺少MainPage.xaml

为什么C#中的类型别名不能在另一个别名中使用?

.NET8支持Vector512,但为什么向量不能达到512位?