gpt4 book ai didi

c# - 告诉 WPF 评估绑定(bind)

转载 作者:太空宇宙 更新时间:2023-11-03 19:17:20 24 4
gpt4 key购买 nike

假设我有一个如下所示的命令执行方法:

    private void Execute()
{
// Bound to a wait indicator in the UI
Searching = true;

// Do some long running process
Thread.Sleep(2000);

Searching = false;
}

当 Searching 设置为 True 时,它​​绑定(bind)到的 UI 元素将不会更新(即使 Searching 发送 OnPropertyChanged 调用)。

但是,一旦 Thread.Sleep 完成,UI 就会处理我的更改并显示 Searching 绑定(bind)到的等待指示器。

现在,我知道传统的智慧是让对长时间运行的进程 (Thread.Sleep) 的调用是异步的。

但假设我没有使用异步库,有没有办法指示 WPF 现在对搜索执行绑定(bind)?

像这样:

    private void Execute()
{
// Bound to a wait indicator in the UI
Searching = true;

// MADE UP CODE
Binding.UpdateBindingNow("Searching");
// END MADE UP CODE


// Do some long running process
Thread.Sleep(2000);

Searching = false;
}

更新:我尝试过的:

  • 使用 Dispatcher 尝试将命令单独发送到 UI。
  • 我还尝试了具有高优先级的 Dispatcher。

最佳答案

您需要将您的工作推送到后台线程中。在 UI 线程可以处理消息之前,绑定(bind)不会更新,这在您的操作完成之前不会发生。

异步是一种方法,但更经典的方法是只使用 BackgroundWorker执行此操作,所有版本的 WPF 都支持此操作。

如果您使用的是 .NET 4,您也可以通过 TPL 执行此操作:

private void Execute()
{
// Bound to a wait indicator in the UI
Searching = true;

Task.Factory.StartNew( () => {
// Do long running work...
}).ContinueWith(t =>
{
// You can do work here, including touching UI controls/collections/etc
Searching = false;
}, TaskScheduler.FromCurrentSynchronizationContext());
}

关于c# - 告诉 WPF 评估绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15211502/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com