我迷失了这个,我希望我的 Viewmodel 使用事件委托,以便我可以订阅它,打开一些对话框并等待对话框结果。稍后 ViewModel 应该对对话结果做任何它想做的事情。这是我实现它的方式(恢复代码):public class MyViewModel(){ public delegate TributaryDocument SearchDocumentEventHandler(); public event SearchDocumentEventHandler SearchDocument; //Command for the search button public CommandRelay SearchDocumentCommand { get; set; } //Document that i found in the dialog. public TributaryDocument Document { get; set; } public MyViewModel() { SearchDocumentCommand = new CommandRelay(DoSearchDocument); } //The command execution public void DoSearchDocument() { //Event used here ! Document = SearchDocument?.Invoke(); }}public class MyUIControl : UserControl{ public MainWindow MainWindow { get; } public MyUIControl() { MainWindow = Application.Current.Windows[0] as MainWindow; DataContextChanged += MyUIControl_DataContextChanged; } private void MyUIControl_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e) { var modelView = (MyViewModel)DataContext; modelView.SearchDocument += MyUIControl_SearchDocument; } private TributaryDocument MyUIControl_SearchDocument() { //Dont know what to do here... i am lost on this part. return await MainWindow.ShowDialog(new MyDocumentSearcherDialog()); }}//The signature for MainWindow.ShowDialogpublic async Task<object> ShowDialog(object dialog){ return await DialogHost.Show(dialog, "MainDialog");}
1 回答

蝴蝶刀刀
TA贡献1801条经验 获得超8个赞
似乎您需要做的就是删除Task.Run(在这种情况下无需卸载到另一个线程)。如果您从内部进行UI工作,肯定Task.Run会给您一个STA 线程异常。
但是,简而言之,Async 和 Await 模式将创建与当前SynchronisationContext的延续,因此无需担心。
public async void DoSearchDocument()
{
await SearchDocument?.Invoke();
}
注意:由于这是一个事件,它是唯一可以使用的地方async void。
- 1 回答
- 0 关注
- 154 浏览
添加回答
举报
0/150
提交
取消