亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

WPF MVVM 異步事件調用

WPF MVVM 異步事件調用

C#
絕地無雙 2022-10-23 15:33:23
我迷失了這個,我希望我的 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。


查看完整回答
反對 回復 2022-10-23
  • 1 回答
  • 0 關注
  • 152 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號