【发布时间】:2021-11-30 02:43:50
【问题描述】:
我想通过选中toggleButton来启动一个进程,并在完成进程后toggleButton被取消选中。
这是我的代码。
Process.xaml:
<ToggleButton Command="{Binding StartProccessCommand}" Content="Proccessing" IsChecked="{Binding isChecked,Mode=TwoWay}"></ToggleButton>
ProcessViewModel.cs:
public class ProccessViewModel: BindableBase
{
private bool _isChecked = false;
public bool isChecked
{
get { return _isChecked; }
set { SetProperty(ref _isChecked, value); }
}
public DelegateCommand StartProccessCommand{ get; set; }
public ProccessViewModel()
{
StartProccessCommand= new DelegateCommand(OnToggleButtonClicked);
}
public async void OnToggleButtonClicked()
{
await Task.Run(() => {
isChecked= true;
for (int i = 0; i < 50000; i++)
{
Console.WriteLine(i);
}
}).ContinueWith((x) =>
{
for (int i = 50000; i < 100000; i++)
{
Console.WriteLine(i);
}
isChecked= false;
}
}
但是当我在检查后立即运行代码 ToggleButton Unchecked。
结果:
选中切换按钮
未选中切换按钮
1
2
.
.
49999
50000
50001
.
.
100000
【问题讨论】:
-
被讨厌的顺序调用在这里:stackoverflow.com/questions/69442685/…。正如所解释的,
ContinueWith没有做你期望它应该做的事情。从那里的评论中,您可以查看该讨论:blog.stephencleary.com/2013/10/…。解决方案是运行任务并逐个单独等待它们,并在所有awaitings 之后才将isChecked设置为false。 -
ToggleButton Checked和ToggleButton Unchecked在输出中来自哪里? -
@Haukinger - 当 isChecked=true;然后 isChecked=flase;运行。
-
为什么
IsChecked绑定在TwoWay模式下?我想它应该遵循isChecked属性。
标签: wpf async-await continuewith