問題
有時候,當程式碼已經轉移到原生專案組件內執行了,此時,您要用非同步的使用核心 PCL 專案內的某個方法,例如,呼叫核心 PCL 專案內的某個方法,使用導航物件進行頁面導航的工作,這個要如何做到呢?
解答
要解決這樣的需求,請依照底下的步驟進行操作。
- 請先取得這個應用程式的 Prism 容器 ( Container ),請使用底下方法取得 Prism 容器
            // 取得 Prism 相依性服務使用到的容器
            IUnityContainer fooContainer = (XFoAuth2.App.Current as PrismApplication).Container;
- 接著,解析出這事件聚合器 (Event Aggregator)介面的實作物件,一旦您取得了這個實作物件,您就可以使用 Prism 的事件訂閱或者發佈事件功能。
            // 取得 IAccountStore 介面實際實作的類別物件
            var fooIEventAggregator = fooContainer.Resolve<IEventAggregator>();
- 在底下的範例中,會根據 e.IsAuthenticated的值內容,使用 Prism 的事件聚合器 (Event Aggregator),送出不同的事件訊息給核心 PCL 專案的訂閱者。
            if (e.IsAuthenticated)
            {
                fooIEventAggregator.GetEvent<AuthEvent>().Publish(AuthEventEnum.身分驗證成功);
            }
            else
            {
                fooIEventAggregator.GetEvent<AuthEvent>().Publish(AuthEventEnum.身分驗證失敗);
            }
- 在核心 PCL 專案內,使用了 Prism 的事件聚合器 (Event Aggregator)訂閱了這個事件,一旦非同步收到這個訊息,就會回到上一頁頁面。
        public oAuthPageViewModel(INavigationService navigationService, IEventAggregator eventAggregator)
        {
            _eventAggregator = eventAggregator;
            _navigationService = navigationService;
            // 訂閱使用者認證結果通知事件,認證成功之後,會收到 Success
            fooSubscriptionToken = _eventAggregator.GetEvent<AuthEvent>().Subscribe(async x =>
              {
                  await _navigationService.GoBackAsync();
              });
        }
 
 
