【发布时间】:2016-08-25 16:15:11
【问题描述】:
我的问题来自 Stephen Cleary 的an article。
基本上是有标签的
<Label Content="{Binding UrlByteCount.Result}"/>
它是由 viewmodel c.tor 设置的
UrlByteCount = new NotifyTaskCompletion<int>(
MyStaticService.CountBytesInUrlAsync("http://www.example.com"));
到目前为止一切顺利。 现在我做一个微不足道的改变:
UrlByteCount = new NotifyTaskCompletion<int>(MyStaticService.ImmediateSet(-1));
已经定义
public static Task<int> ImmediateSet(int res)
{
var tcs = new TaskCompletionSource<int>();
tcs.SetResult(res);
return tcs.Task;
}
显然标签立即显示-1。 好的,那我添加一个带有viewmodel命令绑定的按钮,因为我想在点击按钮的时候设置标签。
跳过所有礼仪部分(委托命令等),核心功能又是:
private void TestLogic()
{
UrlByteCount = new NotifyTaskCompletion<int>( // FIX ME
MyStaticService.CountBytesInUrlAsync("http://www.example.com")); // FIX ME
}
我完全知道它不起作用并且标签的内容将保持 -1,但我想问哪种方法是解决此问题的最佳方法?
问题的第二部分。
假设您已经找到了第一部分的解决方案并且点击按钮异步更改了标签的内容(保持ui响应性),您能否确认以下代码是否是防止“双击”的一致方式(即“多次执行”)?
private async void TestLogic()
{
canRun = false;
((DelegateCommand)TestCommand).RaiseCanExecuteChanged();
await FoundASolution();
canRun = true;
((DelegateCommand)TestCommand).RaiseCanExecuteChanged();
}
private async Task<int> FoundASolution()
{
await Task.Delay(TimeSpan.FromSeconds(10));
return 21;
}
【问题讨论】:
-
为什么它不起作用?如果您在 UrlByteCount 的设置器中引发属性更改事件,它应该可以正常工作。
-
@Evk 我假设它,因为绑定是“UrlByteCount.Result”而不是“UrlByteCount”,所以我认为做 UrlByteCount = new 不干净......不是吗破坏指向.Result的指针?顺便说一句,是的,我看到它确实有效
-
不,当您为 UrlByteCount 分配新值时,绑定知道它已更改(当然假设您引发属性更改事件),即使绑定路径是 UrlByteCount.Whatever1.Whatever2...
-
@Evk 好的,请回答问题。谢谢!
标签: c# wpf mvvm async-await