Ich habe 2 Ansichten und 2 Viewmodel:ReactiveUI Befehl Abmelde
First View:
public partial class FirstView : Page
{
FirstViewModel ViewModel;
public FirstView()
{
ViewModel = new FirstViewModel();
ViewModel.ShowSecondView.Subscribe(_ =>
{
NavigationService.Navigate(new SecondView(ViewModel.ChildViewModel));
});
this.DataContext = ViewModel;
InitializeComponent();
}
}
Erstes Ansichtsmodell:
public class FirstViewModel
{
SecondViewModel ChildViewModel;
public ReactiveCommand<Unit, Unit> ShowSecondView { get; set; }
public FirstViewModel()
{
ChildViewModel = new SecondViewModel();
ShowSecondView = ReactiveCommand.Create(() =>
{
ChildViewModel.Reconfigure(...);
});
}
}
zweiten View:
public partial class SecondView : Page
{
SecondViewModel ViewModel;
public SecondView(SecondViewModel viewModel)
{
ViewModel = viewModel;
ViewModel.GoBack.Subscribe(_ =>
{
DoSomethingHard();
if(NavigationService != null) NavigationService.GoBack();
});
this.DataContext = ViewModel;
InitializeComponent();
}
}
Zweites Ansichtsmodell :
public class SecondViewModel
{
public ReactiveCommand<Unit, Unit> GoBack { get; set; }
public FirstViewModel()
{
VeryLongInitialization();
GoBack = ReactiveCommand.Create(() => { });
}
public void Reconfigure(...)
{ ... }
}
Also, wenn ich FirstViewModel.ShowSecondView
mehrmals laufen und SecondViewModel.GoBack
mehrmals ausgeführt werden, führen DoSomethingHard()
auch mehrmals auf jeder erstellt SecondView.
Warum möchte ich ChildViewModel
in FilstViewModel
einmal erstellen? Weil das Erstellen von SecondViewModel
lange dauert. Und ich nicht jedes Mal neu erstellen SecondViewModel
, aber nur neu konfigurieren.
Meine Frage ist, wie kann ich ViewModel.GoBack.Subscribe
in SecondView
abmelden?
P.S. Vielleicht sollte ich nicht SecondView
in FirstView
neu erstellen, aber es neu konfigurieren sowie SecondViewModel
?
UPDATE 1 (dank Julien Mialon)
I IDisposable goBackSubscr
hinzufügen und es funktioniert! Habe ich recht, um es umzusetzen?
public partial class SecondView : Page
{
SecondViewModel ViewModel;
IDisposable goBackSubscr;
public SecondView(SecondViewModel viewModel)
{
ViewModel = viewModel;
goBackSubscr = ViewModel.GoBack.Subscribe(_ =>
{
DoSomethingHard();
if(NavigationService != null) NavigationService.GoBack();
goBackSubscr.Dispose();
});
this.DataContext = ViewModel;
InitializeComponent();
}
}
ich über IViewFor lesen, aber ich verstehe es nicht (unbedingt) –