猿问

WPF MVVM 异步事件调用

我迷失了这个,我希望我的 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.ShowDialog

public async Task<object> ShowDialog(object dialog)

{

   return await DialogHost.Show(dialog, "MainDialog");

}


绝地无双
浏览 155回答 1
1回答

蝴蝶刀刀

似乎您需要做的就是删除Task.Run(在这种情况下无需卸载到另一个线程)。如果您从内部进行UI工作,肯定Task.Run会给您一个STA 线程异常。但是,简而言之,Async 和 Await 模式将创建与当前SynchronisationContext的延续,因此无需担心。public async void DoSearchDocument(){&nbsp;&nbsp; &nbsp;await SearchDocument?.Invoke();}注意:由于这是一个事件,它是唯一可以使用的地方async void。
随时随地看视频慕课网APP
我要回答