c# - 找出文本框文本是否在 mvvm 模式中没有改变一秒钟

标签 c# wpf mvvm

任何人都可以帮我查明我的文本框的文本是否在 MVVM 模式(使用 WPF)中一秒钟没有改变。

在我的 ViewModel 中,我有一个属性

public String SearchText
{
    get
    {
        return _searchString;
    }

    set
    {
        _searchString = value;
        _functionProvidersView.Refresh();
    }
}

哪里_functionProvidersView类型为 ObservableCollection<FunctionProviderViewModel> .我希望只有当文本一秒钟没有改变时才会刷新。

我试图用 System.Threading 解决这个问题但这并没有解决问题,有人有简单的解决方案吗?

编辑:基于SearchText我的收藏被过滤了。而且因为我的过滤器机制需要一些时间,所以我希望只有在用户一秒钟内没有更改文本框文本(没有输入任何内容)时才会进行过滤。

TextBox 属性 UpdateSourceTrigger设置为 PropertyChanged .我可以将其设置为 LostFocus但这并不是我想要的...

最佳答案

一种方法是使用 timer延迟刷新调用:

public class MainVm
{
    System.Threading.Timer timer;

    private string searchText = string.Empty;
    public string SearchText
    {
        get { return searchText; }
        set
        {
            searchText = value;

            timer.Change(1000, System.Threading.Timeout.Infinite); //reset the timer
        }
    }

    public MainVm()
    {
        timer = new System.Threading.Timer(RefreshView, 
                                           null, 
                                           System.Threading.Timeout.Infinite,
                                           System.Threading.Timeout.Infinite);
    }

    private void RefreshView(object state)
    {
        //Here you need to use the dispatcher because the callback is called
        //from a non-UI thread
        Application.Current.Dispatcher.Invoke(new Action(() =>
            _functionProvidersView.Refresh()
        );
    }
}

这样,RefreshView 方法将在您停止输入 1 秒后调用

关于c# - 找出文本框文本是否在 mvvm 模式中没有改变一秒钟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24052351/

相关文章:

c# - "Inheritance"属性 : what does it do?

c# - 如何将基类型列表转换为派生类型列表

c# - 使用 Entity Framework 的输出参数执行 SQL 存储过程

c# - 使用 View 模型在 TreeView 中展开路径

c# - 从 UserControl 中的资源访问代码隐藏中的变量

c# - 从在 Dispatcher 上调用的异步操作返回值

wpf - 使用 iValueConverter 格式化 TextBlock 的部分文本

c# - WPF - MVVM 文本框限制为特定字符

c# - ListCollectionView分组已分组的项目

wpf - 以编程方式选择并突出显示数据网格MVVM