我想通过检查toggleButton来启动一个进程,完成进程后toggleButton被选中
这是我的代码。
过程中。xaml:
<ToggleButton Command="{Binding StartProccessCommand}" Content="Proccessing" IsChecked="{Binding isChecked,Mode=TwoWay}"></ToggleButton>
ProccessViewModel.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检查
ToggleButton未经检查的
1
2
。
。
49999
50000
50001
。
。
100000
为什么使用ContinueWith
和await
?这是没有意义的,因为OnToggleButtonClicked
的剩余部分将在等待的Task
完成后执行。
设置属性,等待第一个Task
,然后等待另一个Task
,并将属性设置回false
:
public async void OnToggleButtonClicked()
{
isChecked = true;
await Task.Run(() => {
for (int i = 0; i < 50000; i++)
{
Console.WriteLine(i);
}
});
await Task.Run(() =>
{
for (int i = 50000; i < 100000; i++)
{
Console.WriteLine(i);
}
});
isChecked = false;
}