【发布时间】:2016-07-22 11:19:54
【问题描述】:
我有一个这样的ViewModel:
public class WelcomeWindowVm : ViewModel
{
private ViewModel view;
public WelcomeWindowVm(){
this.View = new LoginVm() {
Completed += (o, e) => {
this.View = new OtherVm(e.User){
Completed += (o, e) =>; // and so on
}
}
};
}
public ViewModel View {
get {
return this.view;
}
set {
this.view = value;
this.OnPropertyChanged(nameof(this.View));
}
}
}
LoginVm 是另一个 Viewmodel,其 Completed 事件在其上的命令完成时触发(该事件仅在使用正确的登录凭据时触发)。 OtherVm 是另一个虚拟机,它的完成事件因任何原因而被触发。
我使用DataTemplate 渲染View。例如:
<Window.Resources>
<DataTemplate DataType="vm:LoginVm">
Textboes and buttons here
</DataTemplate>
<DataTemplate DataType="vm:OtherVm">
...
</DataTemplate>
</Window.Resources>
<ContentControl Content={Binding View} />
此窗口的 DataContext 设置为上面的WelcomeWindowVm 类,在ShowDialog 之前。
这很好用。当使用 ShowDialog 显示窗口时,会显示LoginVm。然后OtherVm当LoginVm的任何任务完成时,以此类推。
现在我想将 Completion 的东西转换为 Async/await 模式。 LoginVm 现在看起来像这样:
public LoginVm{
...
private TaskCompletionSource<User> taskCompletionSource = new TaskCompletionSource<User>();
...
// This is the Relay command handler
public async void Login()
{
// Code to check if credentials are correct
this.taskCompletionSource.SetResult(this.user);
// ...
}
public Task<User> Completion(){
return this.taskCompletionSource.Task;
}
}
而不是这个:
public LoginVm{
public event EventHandler<CustomArgs> Completed;
// This is the Relay command handler
public async void Login()
{
// Code to check if credentials are correct
OnCompleted(this.user);
// ...
}
}
这样我就可以这样使用它了:
public WelcomeWindowVm(){
var loginVm = new LoginVm();
this.View = new LoginVm();
User user = await loginVm.Completion();
var otherVm = new OtherVm(user);
this.View = otherVm;
Whatever wev = await otherVm.Completion();
//And so on
}
但是我不能在构造函数中使用等待,即使我为此使用异步方法,由于ShowDialog 阻塞,在调用ShowDialog 之后我将如何在另一个类中调用它?
我认为使用async void 会起作用。但据我所知,除非我在事件处理程序中使用它,否则应该避免它。
也许使用async Task 方法而不是await 它?
【问题讨论】:
标签: c# wpf mvvm async-await task