我迷失了這個(gè),我希望我的 Viewmodel 使用事件委托,以便我可以訂閱它,打開(kāi)一些對(duì)話框并等待對(duì)話框結(jié)果。稍后 ViewModel 應(yīng)該對(duì)對(duì)話結(jié)果做任何它想做的事情。這是我實(shí)現(xiàn)它的方式(恢復(fù)代碼):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貢獻(xiàn)1801條經(jīng)驗(yàn) 獲得超8個(gè)贊
似乎您需要做的就是刪除Task.Run(在這種情況下無(wú)需卸載到另一個(gè)線程)。如果您從內(nèi)部進(jìn)行UI工作,肯定Task.Run會(huì)給您一個(gè)STA 線程異常。
但是,簡(jiǎn)而言之,Async 和 Await 模式將創(chuàng)建與當(dāng)前SynchronisationContext的延續(xù),因此無(wú)需擔(dān)心。
public async void DoSearchDocument()
{
await SearchDocument?.Invoke();
}
注意:由于這是一個(gè)事件,它是唯一可以使用的地方async void。
- 1 回答
- 0 關(guān)注
- 146 瀏覽
添加回答
舉報(bào)
0/150
提交
取消