我有一个 Textbox
,它有一个 KeyDown
事件。此事件与 ViewModel 中的事件处理程序绑定(bind)。下面是示例代码:
<TextBox x:Name="textBox" Text="{Binding TextBoxText, UpdateSourceTrigger=PropertyChanged}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="KeyDown">
<cmd:EventToCommand Command="{Binding Path=TextBoxKeyDownEvent}" PassEventArgsToCommand="True" />
</i:EventTrigger>
</i:Interaction.Triggers>
<TextBox.InputBindings>
确实,一旦用户开始在文本框中书写,就会调用 ViewModel 中的后端事件处理程序。但我不想为每个 KeyDown 操作调用事件处理程序。我想在用户开始在文本框中输入并停止至少 N 毫秒时调用事件处理程序。这意味着我需要为事件设置延迟计时器。谁能指导我如何在 MVVM 中实现这一点?
最佳答案
您可以使用 BindingBase.Delay
属性:
<TextBox x:Name="textBox" Text="{Binding TextBoxText, Delay=500, UpdateSourceTrigger=PropertyChanged}" />
这将在用户更改后仅 500 毫秒修改 View 模型中的 TextBoxText
属性。然后,在您的 setter 中,您可以调用任何您想要执行的代码。
private string textBoxText;
public string TextBoxText
{
get { return textBoxText; }
set
{
// Setter will be called only 500 milliseconds after the user has entered text.
if (textBoxText != value)
{
textBoxText = value;
RaisePropertyChanged("TextBoxText");
// Handle text change.
DoStuff();
}
}
}
编辑:
如果您希望在代码中更改属性时也发生延迟,您可以使用类似于此处提到的解决方案的方法:Timer to fire an event WPF
关于c# - KeyDown 事件的延迟计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26075310/