我一直在使用ReactiveUI來創建viewmodels並將它們綁定到我的WPF視圖。在這些視圖模型中,我使用UserError來封裝異常並將它們轉發給關聯的視圖。C#ReactiveUI UserError錯誤處理程序
但是,我已經注意到,當引發UserError時,它並不總是以期望的處理程序結束。爲了解決這個問題,我將UserError和註冊處理程序分爲僅使用此子類的UserError.RegisterHandler<MyUserErrorSubclass>(myHandler)
這看起來可行,但並未完全解決問題。 我現在有兩個相同viewmodel和相關視圖的實例,但在一個viewmodel中拋出的UserError最終會出現錯誤的視圖。這是一個問題,因爲我想顯示錯誤消息,但它顯示在錯誤的視圖中。
示例代碼:
class ViewModel : ReactiveObject {
...
public ReactiveCommand<object> ExampleCommand { get; }
ViewModel(){
...
ExampleCommand.ThrownExceptions.Subscribe(ex => UserError.Throw(new UserError("Error!")));
}
}
class View : IViewFor<ViewModel> {
...
Label exampleLabel;
View(){
...
UserError.RegisterHandler(userError => {
exampleLabel.Text = userError.ErrorMessage;
});
...
}
...
}
ViewModel aModel = new ViewModel();
View aView = new View { ViewModel = aModel};
ViewModel bModel = new ViewModel();
View bView = new View { ViewModel = bModel};
調用aModel.Example()
套bView.exampleLabel
,而我需要設置aView.exampleLabel
什麼是解決這一問題的最佳方法是什麼?